Click here to Skip to main content
15,880,967 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, i'm trying to do the following yet i can't seem to get any print message:
SQL
SET @dynamicSQLCommandC = 
		'DECLARE test_cursor CURSOR
		FOR 
		SELECT *
		FROM ' +@CurrentTable+ 
		'
		OPEN test_cursor	
		FETCH NEXT FROM test_cursor INTO ' +@CurrentRow+ '
		WHILE @@FETCH_STATUS = 0
		BEGIN
			PRINT ''Your dynamically created Cursor works mate!''
			FETCH NEXT FROM test_cursor INTO ' +@CurrentRow+ '
		END
		CLOSE test_cursor
		DEALLOCATE test_cursor'
EXEC sp_executesql @dynamicSQLCommandC

I have tested the part below dynamically in the same scope and it works so the problem doesn't stem from it:
SQL
SELECT *
FROM ' +@CurrentTable

Dynamic SQL form:
SQL
SET @dSQL =
        '
        SELECT *
        FROM ' +@CurrentTable
EXEC sp_executesql @dSQL

Thanks for your guidance.
Posted
Updated 15-Sep-14 23:20pm
v6

1 solution

Hi,

Do you need to open and iterate through the cursor dynamicaly?

What happens when you declare your cursor like below, and open and iterate outside of the dynamic sql statement?

SQL
DECLARE @SQL NVARCHAR(4000)
SET @SQL = 
  'DECLARE test_cursor CURSOR FOR 
  SELECT * FROM ' +@CurrentTable

EXEC sp_executesql @SQL

OPEN test_cursor	
 FETCH NEXT FROM test_cursor INTO @CurrentRow
 WHILE @@FETCH_STATUS = 0
  BEGIN
   PRINT 'Your dynamically created Cursor works mate!'
  FETCH NEXT FROM test_cursor INTO @CurrentRow
  END
CLOSE test_cursor
DEALLOCATE test_cursor'


Hope it helps, and let me know how you get on?
 
Share this answer
 
Comments
YourAverageCoder 16-Sep-14 6:02am    
That works but i need to know if cursors work inside a dynamic SQL Command.
hypermellow 16-Sep-14 6:22am    
I don't think you can declare, open and iterate a cursor inside a dynamic sql command.

Here's an article you should read:
http://www.codeproject.com/Articles/489617/CreateplusaplusCursorplususingplusDynamicplusSQLpl

Hope it helps.
YourAverageCoder 16-Sep-14 6:26am    
It helps a lot. Thanks.
hypermellow 16-Sep-14 6:28am    
Glad it helped. Cheers.

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