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
FETCH NEXT FROM @result_Cursor INTO @x, @y