score:1

Accepted answer

You can use this sample, i used a system table to get the first 10 rows, but you can create your own cursor.

DECLARE @cursor_name AS NVARCHAR(100)

SET @cursor_name = 'sampleCursor' 
                   + Replace(Cast(Newid() AS VARCHAR(36)), '-', '') 

DECLARE @cursor_sql AS NVARCHAR(max) 

SET @cursor_sql = N'   DECLARE @name nvarchar(10)  DECLARE ' + @cursor_name + N' CURSOR FOR   select top 10 name from sys.all_columns OPEN ' + @cursor_name 
                  + N' FETCH NEXT FROM ' + @cursor_name 
                  + N' INTO @name WHILE @@FETCH_STATUS <> -1 BEGIN print @name FETCH NEXT FROM  ' + @cursor_name + N' INTO @name end CLOSE  ' 
                  + @cursor_name + N' DEALLOCATE  ' + @cursor_name 

PRINT @cursor_sql 

EXECUTE Sp_executesql 
  @cursor_sql 

To the cursor name is added a guid, to guarantee that is always different.

Then a query is created and executed based on that name.

Hope it helps!

score:0

You need to run it inside a dynamic sql statement. As a starting point you can check this question: Using a cursor with dynamic SQL in a stored procedure


More questions

More questions with similar tag