TSQL Cursor how to check if already declared and thus deallocate
You can declare the Cursor as a variable then it will be closed and deallocated automatically when it goes out of scope. Example of using this in conjunction with dynamic SQL below.
DECLARE @C1 AS CURSOR;
SET @C1 = CURSOR FAST_FORWARD
FOR SELECT name
FROM master..spt_values
WHERE name <> ''
ORDER BY name;
OPEN @C1;
EXEC sp_executesql N'
DECLARE @name VARCHAR(50)
FETCH NEXT FROM @C1 INTO @name;
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @name
FETCH NEXT FROM @C1 INTO @name;
END
', N'@C1 CURSOR', @C1 = @C1