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 ('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).
EXEC ('SELECT * FROM ' + #TableNameParam + ' WHERE STATUS=1')
How is your data obtained in your temporary table?
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.