Reputation: 105
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
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
Reputation: 2720
You should take a look at The Curse and Blessings of Dynamic SQL
Upvotes: 2