Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
declare @str nvarchar(1000)
declare @cstr nvarchar(2000)


DECLARE @c1 CURSOR
   set @str=N'SELECT EmpID FROM  Emp where ' + @whereqry 
    
 set @cstr = 'SET @c1  = CURSOR FOR ' + @str

 exec sp_executesql @cstr 
 open @c1
FETCH NEXT
FROM @c1 INTO @id
WHILE @@FETCH_STATUS = 0
BEGIN
........

FETCH NEXT
FROM @c1 INTO @id
END
CLOSE @c1
DEALLOCATE @c1

When i execute procedure error comes

Must declare the scalar variable "@c1".
The variable '@c1' does not currently have a cursor allocated to it.

Can someone shed some light?
Posted
Updated 10-Jun-12 22:11pm
v2

1 solution

You cant (I believe) have a dynamic cursor this way. You would need to have the whole cursor declaration in a string and execute the sql. i.e.

SQL
declare @str nvarchar(1000)
declare @cstr nvarchar(2000)
 
set @str=N'SELECT EmpID FROM  Emp where ' + @whereqry 
set @cstr = 'DECLARE c1 CURSOR FOR ' + @str

exec sp_executesql @cstr 
open c1
FETCH NEXT
FROM c1 INTO @id
WHILE @@FETCH_STATUS = 0
BEGIN
........
 
FETCH NEXT
FROM c1 INTO @id
END
CLOSE c1
DEALLOCATE c1


reference : http://stackoverflow.com/questions/1045880/using-a-cursor-with-dynamic-sql-in-a-stored-procedure[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900