Transact-SQL 参考

DEALLOCATE

删除游标引用。当释放最后的游标引用时,组成该游标的数据结构由 Microsoft® SQL Server™ 释放。

语法

DEALLOCATE { { [ GLOBAL ] cursor_name } | @cursor_variable_name }

参数

cursor_name

是已声明游标的名称。当全局和局部游标都以 cursor_name 作为它们的名称存在时,如果指定 GLOBAL,则 cursor_name 引用全局游标,如果未指定 GLOBAL,则 cursor_name 引用局部游标。

@cursor_variable_name

cursor 变量的名称。@cursor_variable_name 必须为 cursor 类型。

注释

对游标进行操作的语句使用游标名称或游标变量引用游标。DEALLOCATE 删除游标与游标名称或游标变量之间的关联。如果一个名称或变量是最后引用游标的名称或变量,则将释放游标,游标使用的任何资源也随之释放。用于保护提取隔离的滚动锁在 DEALLOCATE 上释放。用于保护更新(包括通过游标进行的定位更新)的事务锁一直到事务结束才释放。

DECLARE CURSOR 语句分配游标并使其与游标名称关联:

DECLARE abc SCROLL CURSOR FOR
SELECT * FROM authors

游标名称与某个游标关联之后,该游标在释放之前不能用作相同作用域(GLOBAL 或 LOCAL)内另一个游标的名称。

游标变量使用下列两种方法之一与游标关联:

DEALLOCATE @cursor_variable_name 语句只删除对游标命名变量的引用。直到批处理、存储过程或触发器结束时变量离开作用域,才释放变量。在 DEALLOCATE @cursor_variable_name 语句之后,可以使用 SET 语句使变量与另一个游标关联。

USE pubs
GO
DECLARE @MyCursor CURSOR
SET @MyCursor = CURSOR LOCAL SCROLL FOR
SELECT * FROM titles

DEALLOCATE @MyCursor

SET @MyCursor = CURSOR LOCAL SCROLL FOR
SELECT * FROM sales
GO

不必显式释放游标变量。变量在离开作用域时被隐性释放。

权限

默认情况下,将 DEALLOCATE 权限授予任何有效用户。

示例

下面的脚本显示游标如何持续到最后的名称或持续到引用它们的变量已释放。

USE pubs
GO
-- Create and open a global named cursor that
-- is visible outside the batch.
DECLARE abc CURSOR GLOBAL SCROLL FOR
SELECT * FROM authors
OPEN abc
GO
-- Reference the named cursor with a cursor variable.
DECLARE @MyCrsrRef1 CURSOR
SET @MyCrsrRef1 = abc
-- Now deallocate the cursor reference.
DEALLOCATE @MyCrsrRef1
-- Cursor abc still exists.
FETCH NEXT FROM abc
GO
-- Reference the named cursor again.
DECLARE @MyCrsrRef2 CURSOR
SET @MyCrsrRef2 = abc
-- Now deallocate cursor name abc.
DEALLOCATE abc
-- Cursor still exists, referenced by @MyCrsrRef2.
FETCH NEXT FROM @MyCrsrRef2
-- Cursor finally is deallocated when last referencing
-- variable goes out of scope at the end of the batch.
GO
-- Create an unnamed cursor.
DECLARE @MyCursor CURSOR
SET @MyCursor = CURSOR LOCAL SCROLL FOR
SELECT * FROM titles
-- The following statement deallocates the cursor
-- because no other variables reference it.
DEALLOCATE @MyCursor
GO

请参见

CLOSE

游标

DECLARE @local_variable

FETCH

OPEN