Don
Don

Reputation: 105

How can I set a cursor to a dynamically created SQL query in stored procedure

I want to create a dynamic command using @sqlQuery variable. I've also declared a cursor (example: @myCursor). How can I "SET @myCursor = CURSOR FOR @sqlQuery". The syntax I just noted doesn't work. I am using SQL 2000.

Upvotes: 1

Views: 1354

Answers (2)

Anthony Faull
Anthony Faull

Reputation: 17957

You can do it using sp_executesql. Just be sure to open the cursor within the dynamic SQL.

CREATE PROCEDURE OpenCursor (@query nvarchar(max), @cur cursor VARYING OUTPUT)
AS
    DECLARE @sql nvarchar(max)
    SET @sql = N'SET @cur = CURSOR STATIC FOR ' + @query + '; OPEN @cur'
    EXEC sp_executesql @sql, N'@cur cursor OUTPUT', @cur OUTPUT
GO

DECLARE @cur cursor
EXEC OpenCursor 'SELECT * FROM sysobjects', @cur OUTPUT
FETCH NEXT FROM @cur

Upvotes: 1

Bruno Costa
Bruno Costa

Reputation: 2720

You should take a look at The Curse and Blessings of Dynamic SQL

Upvotes: 2

Related Questions