[英]SQL Server 2008 R2: Return result from stored procedure and insert into temp table
I have a table testing
with some data: 我有一些表
testing
一些数据:
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. 注意 :执行存储过程后,我想将结果插入到
temptable
,我不想在之前用结构声明。
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 插入到表/ temptable中的这种简单语法是一个过程的结果集
INSERT INTO TempTable
EXEC MyProc
But the gotcha with this approach is that TempTable should already exist before you can do the above. 但是这种方法的问题是TempTable应该已经存在,然后才能执行上述操作。
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
. 调用存储过程并将其结果集插入表时,无法像使用select语句那样动态创建表
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 .... 现在,因为一些表可以有50列并找到它们的DDL并创建表,然后才能执行该过程,有一种简单的方法可以解决类似....
-- 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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.