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.