简体   繁体   中英

SQL Server 2008 R2: Return result from stored procedure and insert into temp table

I have a table testing with some data:

Table:

select * from testing;

cola colb
---------
 A    B
 C    D
 C    X
 S    T
 S    Q

Stored procedure:

CREATE PROC spTesting
   @TableName nvarchar(max)
AS
   DECLARE @sql nvarchar(max)

   SET @sql = 'SELECT * from '+ @TableName + ''

   EXEC(@sql)
GO

Executing stored procedure:

execute spTesting 'testing'

I will get the result:

cola colb
---------
 A    B
 C    D
 C    X
 S    T
 S    Q

Note : After executing the stored procedure, I want to insert results into temptable which I don't want to declare with the structure before.

Like:

 select * into temptable from execute spTesting 'testing'

There is this simple syntax of inserting into a table/temptable, a result set of a procedure

INSERT INTO TempTable
EXEC MyProc

But the gotcha with this approach is that TempTable should already exist before you can do the above.

When calling a stored procedure and inserting its result set into a table you cannot create a table on the fly like you can do with a select statement select * INTO temptabe From tablename .

You will need to create this table first and then Insert into it from your stored procedure.

Now since some tables can have 50 columns and finding their DDL and creating table before you can execute the procedure there is a simple way around something like ....

-- before you execute the procedure 

SELECT * INTO TempTable FROM TargetTable WHERE 1 =2 

-- this will create an empty table with matching schema of your TargetTable 
-- Now execute the procedure 

INSERT INTO TempTable 
EXECUTE spTesting 'TargetTable'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM