[英]Insert into temp table from exec call stored procedure
I have a stored procedure where I insert a table into a temporary table and then I read that temp table row by row using a cursor: 我有一个存储过程,在其中将表插入临时表,然后使用光标逐行读取该临时表:
USE [TEST_DB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[returnValidationFailures]
AS
BEGIN
SET NOCOUNT ON;
SELECT TOP 0 * INTO TempTbl FROM USER
DECLARE cursor1 CURSOR FAST_FORWARD FOR
SELECT *
FROM USER
OPEN cursor1
INSERT INTO TempTbl
EXEC ('fetch next from cursor1')
WHILE @@FETCH_STATUS = 0
INSERT INTO TempTbl
EXEC ('fetch next from cursor1')
CLOSE cursor1
DEALLOCATE cursor1
SELECT *
FROM TempTbl
DROP TABLE TempTbl
END
What I want here is to send the table name through a paramater like: 我想在这里通过类似这样的参数发送表名:
@TableNameParam varchar(10)
And then insert into temp table like: 然后插入到临时表中,如下所示:
SELECT TOP 0 * INTO TempTbl FROM @TableNameParam
DECLARE cursor1 CURSOR FAST_FORWARD FOR
SELECT *
FROM @TableNameParam
This doesn't work (obviously). 这是行不通的(显然)。 But every other method I tried didn't work.
但是我尝试的所有其他方法都行不通。 Is there any way I can set the data of an EXEC call like:
有什么办法可以设置EXEC调用的数据,例如:
EXEC ('SELECT * FROM ' + @TableNameParam
' WHERE STATUS=1')
into the temp table? 进入临时表?
Note: I DO NOT know the table structure. 注意: 我不知道表结构。
I'm not very sure I understand what is your final scope, but my advise is to use a set-based approach. 我不太确定我了解您的最终范围是什么,但是我的建议是使用基于集合的方法。
To respond directly to you question, you should take into account the usage of temporary tables (#TempTable) instead of table variables (@TempTable). 要直接回答您的问题,应考虑使用临时表(#TempTable)而不是表变量(@TempTable)。
EXEC ('SELECT * FROM ' + #TableNameParam + ' WHERE STATUS=1')
How is your data obtained in your temporary table? 如何在临时表中获取数据?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.