Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server: Put stored procedure result set into a table variable without specifying its schema

I have a stored procedure with many parameters.

I want to insert (or maybe select) like this:

INSERT INTO @TEMP_TABLE
    EXECUTE STORED_PROCEDURE

without defining the schema of @TEMP_TABLE.

like image 810
naeron84 Avatar asked Aug 30 '11 16:08

naeron84


People also ask

How do I insert a stored procedure result into a table?

When the stored procedure returns a lot of columns and you do not want to manually "create" a temporary table to hold the result, I've found the easiest way is to go into the stored procedure and add an "into" clause on the last select statement and add 1=0 to the where clause.

How do I return a stored procedure to a variable in SQL Server?

You can use the return statement inside a stored procedure to return an integer status code (and only of integer type). By convention a return value of zero is used for success. If no return is explicitly set, then the stored procedure returns zero. You should use the return value for status codes only.

Can we return table variable from stored procedure?

You can't technically return "a table", but you can return a result set and using INSERT INTO .. EXEC ... syntax, you can clearly call a PROC and store the results into a table type.


2 Answers

You cannot do this with a @tablevariable.

The work around in the link posted by Joe uses SELECT ... INTO.

This is not currently supported by table variables (and won't ever be from the response to this connect item) as the schema for table variables needs to be known at compile time.

like image 137
Martin Smith Avatar answered Oct 19 '22 04:10

Martin Smith


for example:

declare @temptable2 as table
(
 DatabaseName nvarchar(128),
 dbsize nvarchar(128),
 owner varchar(128),
 dbid nvarchar(128),
 created nvarchar(128),
 status nvarchar(128),
 compatibility_level nvarchar(128)
)

INSERT INTO @temptable2
EXEC ('sp_helpdb')
like image 43
skorpk Avatar answered Oct 19 '22 03:10

skorpk