1

I am building a stored procedure in Sql Server 2008. Stored Procedure has two arguments which are the column names of a table. In stored procedure I used dynamic query for fetching data of these two columns with the help of Cursor.

Code:

    Create PROCEDURE TestSP
(
@firstAttribute nvarchar(max),
@secondAttribute nvarchar(max)
)
AS 
DECLARE @x FLOAT
DECLARE @y INT
DECLARE @query nvarchar(max)
DECLARE @cursor_query nvarchar(max)
DECLARE @result_Cursor as cursor

BEGIN
SET @query = 'Select '+ @firstAttribute+','+@secondAttribute+' from TBL_TEST_DATA_NEW'
SET @cursor_query =' set @cursor = cursor for ' + @query +' open @cursor;'

PRINT 'CURSOR_QUERY'+@cursor_query

exec sys.sp_executesql
    @cursor_query
    ,N'@cursor cursor output'
    ,@result_Cursor output

FETCH NEXT FROM result_Cursor INTO @x, @y

But when I am executing this SP it is giving me following error

Msg 16916, Level 16, State 1, Procedure TestSP, Line 33
A cursor with the name 'result_Cursor' does not exist.

Execute Command :

Exec TestSP "Column_1","Column_2"

Can someone tell me why I am getting this error

Please Help..

Thanks

1
  • 1
    Add @ to your parameter result_Cursor and retry: FETCH NEXT FROM @result_Cursor INTO @x, @y Commented Sep 27, 2013 at 6:23

3 Answers 3

1

The error is saying that Cursor does not exist. You can't start with "set cursor". Also cursor name is without @.

So try using

declare cursorNameHere cursor for SELECT ...
open cursorNameHere
Sign up to request clarification or add additional context in comments.

Comments

1

@result_Cursor is a variable, just change your last line to

FETCH NEXT FROM @result_Cursor INTO @x, @y

see example on sql fiddle demo

Comments

0

change

PRINT 'CURSOR_QUERY'+@cursor_query

to

PRINT 'CURSOR_QUERY '+@cursor_query

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.