I wonder whether cursor for query with @variable parameter can be re-used (CLOSE + OPEN) when value of the @variable changes. To me it looks that it always needs CLOSE + DEALLOCATE + DECLARE + OPEN to take new value of the @variable into effect. Perhaps no big deal, but I wanted to know whether DEALLOCATE + DECLARE can be left out between uses.
Here you have complete simple example to try it out:
DECLARE @ta TABLE (a int);
INSERT INTO @ta (a) VALUES (1),(2),(4),(8),(16),(32),(64);
---------
DECLARE @current_a int;
DECLARE @threshold int = 12;
DECLARE crs1 CURSOR FOR SELECT a FROM @ta WHERE a < @threshold;
--- first cursor use
OPEN crs1;
FETCH NEXT FROM crs1 INTO @current_a;
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @threshold, @current_a
FETCH NEXT FROM crs1 INTO @current_a;
END;
CLOSE crs1;
DEALLOCATE crs1; -- can this be left out?
SET @threshold = 3;
DECLARE crs1 CURSOR FOR SELECT a FROM @ta WHERE a < @threshold; -- can this be left out?
--- second cursor use
OPEN crs1;
FETCH NEXT FROM crs1 INTO @current_a;
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @threshold, @current_a
FETCH NEXT FROM crs1 INTO @current_a;
END;
CLOSE crs1;
DEALLOCATE crs1;
This was linearized example, but the question applies also to nested cursors when outer cursor changes the query parameter of inner cursor.
cursor variable? Check demo