Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to insert values into a table var from an SP

Status
Not open for further replies.

RRinTetons

IS-IT--Management
Jul 4, 2001
333
0
0
US
I use temp tables to accomplish this, but I'd like to know how to do it with table vars.

I can create a temp table and call an existing sp to put data into it. The sp returns a selection that populates the temp table. The syntax for that is like:

CREATE TABLE #MyTempTable
<table def>

INSERT #MyTempTable
SELECT dbo.MySP(var1, var2)

and all is well

But I wanted to do it as

DECLARE @MyTempTable TABLE
<table def>

then the same INSERT doesn't work.

How do I populate the TABLE var in this case? Is it some sort of an assignment statement?

-
Richard Ray
Jackson Hole Mountain Resort
 
The syntax is as follows:

Code:
INSERT INTO @MyTempTable 
EXEC MyStoredProc {Parameters}
 
I gives back an error -

'EXECUTE cannot be used as a source when inserting into a table variable. Number:197 Severity:15 State:1'.

-
Richard Ray
Jackson Hole Mountain Resort
 
Nope, the temp table will work fine, I just wanted to start using table vars since I'm not familiar with them. Now I know a useful thing about them :). This app is moving onto SQL Server 2005 in 2 weeks, I'll try it again the next time I have a similar need.

-
Richard Ray
Jackson Hole Mountain Resort
 
Hi tons,

Can you use a function instead of procedure?
If that is the case, try out the following code and correct accordingly it would work for u...

DECLARE @TAB AS TABLE
(ID INT,
TEXTDATE NVARCHAR(100))

//calling function to get the values to be inserted into tablevariables
INSERT INTO @TAB
SELECT * from dbo.TEST()

SELECT * FROM @TAB

//Function which u are calling above
CREATE function TEST()
RETURNS TABLE AS
RETURN (select 20 as ID,'test' as textresult)

Thanks,
AP
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top