Hi,
I am having problem using FETCH cursor statement inside a EXEC statement. I need to use EXEC because there is a variable inside the FETCH statement. Thank you.
Here is a sample data:
SELECT 'A' AS LETTER INTO ALPHABET
UNION
SELECT 'B'
UNION
SELECT 'C'
Here is a query I like to execute:
DECLARE SET_ALPHA CURSOR FOR SELECT * FROM ALPHABET
OPEN SET_ALPHA
DECLARE @PrimaryKey VARCHAR(50)
FETCH NEXT FROM SET_ALPHA INTO @PrimaryKey--Change this
CLOSE SET_ALPHA
DEALLOCATE SET_ALPHA
Now I like to change SET_ALPHA cursor in the Fetch statement. I am going to leave OPEN, CLOSE, DEALLOCATE without using variable for testing purpose, because I know it works!! Here is the new query:
DECLARE SET_ALPHA CURSOR FOR SELECT * FROM ALPHABET
OPEN SET_ALPHA
DECLARE @PrimaryKey VARCHAR(50)
DECLARE @cursor VARCHAR(500)
SET @cursor ='SET_ALPHA'
DECLARE @FetchStatement VARCHAR(500)
SET @FetchStatement="FETCH NEXT FROM "+@cursor+" INTO @PrimaryKey"
PRINT @FetchStatement
EXEC (@FetchStatement)
CLOSE SET_ALPHA
DEALLOCATE SET_ALPHA
Here is the error message:
Server: Msg 137, Level 15, State 1, Line 1
Must declare the variable '@PrimaryKey'.
Thank you for any assistance.
Chaoma
I am having problem using FETCH cursor statement inside a EXEC statement. I need to use EXEC because there is a variable inside the FETCH statement. Thank you.
Here is a sample data:
SELECT 'A' AS LETTER INTO ALPHABET
UNION
SELECT 'B'
UNION
SELECT 'C'
Here is a query I like to execute:
DECLARE SET_ALPHA CURSOR FOR SELECT * FROM ALPHABET
OPEN SET_ALPHA
DECLARE @PrimaryKey VARCHAR(50)
FETCH NEXT FROM SET_ALPHA INTO @PrimaryKey--Change this
CLOSE SET_ALPHA
DEALLOCATE SET_ALPHA
Now I like to change SET_ALPHA cursor in the Fetch statement. I am going to leave OPEN, CLOSE, DEALLOCATE without using variable for testing purpose, because I know it works!! Here is the new query:
DECLARE SET_ALPHA CURSOR FOR SELECT * FROM ALPHABET
OPEN SET_ALPHA
DECLARE @PrimaryKey VARCHAR(50)
DECLARE @cursor VARCHAR(500)
SET @cursor ='SET_ALPHA'
DECLARE @FetchStatement VARCHAR(500)
SET @FetchStatement="FETCH NEXT FROM "+@cursor+" INTO @PrimaryKey"
PRINT @FetchStatement
EXEC (@FetchStatement)
CLOSE SET_ALPHA
DEALLOCATE SET_ALPHA
Here is the error message:
Server: Msg 137, Level 15, State 1, Line 1
Must declare the variable '@PrimaryKey'.
Thank you for any assistance.
Chaoma