我想知道当@variable
的值发生变化时,是否可以重复使用CLOSE
参数查询的光标(OPEN
+ @variable
)。对我而言,它始终需要CLOSE
+ DEALLOCATE
+ DECLARE
+ OPEN
才能使@variable
的新值生效。也许没什么大不了的,但我想知道在使用之间是否可以省略DEALLOCATE
+ DECLARE
。
这里有完整的简单示例来试用:
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;
这是线性化的示例,但当外部游标更改内部游标的查询参数时,该问题也适用于嵌套游标。
答案 0 :(得分:1)
一种方法是使用cursor variable
:
DECLARE { { @local_variable [AS] data_type | [ = value ] } | { @cursor_variable_name CURSOR }
@cursor_variable_name
是游标变量的名称。游标变量名必须以at(@)符号开头,并符合标识符规则。
<强> CURSOR 强>
指定变量是本地游标变量。
游标变量:
可以是游标类型或其他游标变量的目标。有关更多信息,请参阅SET @local_variable。
如果游标变量没有游标,可以在EXECUTE语句中作为输出游标参数的目标引用 目前已分配给它。
应被视为指向光标的指针。
DECLARE crs1 CURSOR FOR SELECT a FROM @ta WHERE a < @threshold;
-- could be changed to
DECLARE @crs1 CURSOR;
SET @crs1 = CURSOR FOR SELECT a FROM @ta WHERE a < @threshold;
的 LiveDemo
强>