DEALLOCATE (Transact-SQL)
SQL Server 2005
移除資料指標參考。當取消配置最後一個資料指標參考時,Microsoft SQL Server 會釋出組成資料指標的資料結構。
處理資料指標的陳述式會利用資料指標名稱或資料指標變數來參考資料指標。DEALLOCATE 會移除資料指標和資料指標名稱或資料指標變數之間的關聯。如果名稱或變數是最後一個參考資料指標的項目,就會取消配置資料指標,釋出資料指標所用的任何資源。在 DEALLOCATE 時,會釋出用來保護提取隔離的捲動鎖定。用來保護更新 (其中包括透過資料指標所進行的定位更新) 的交易鎖定,會保留到交易結束時。
DECLARE CURSOR 陳述式會配置資料指標,將資料指標關聯於資料指標名稱。
DECLARE abc SCROLL CURSOR FOR SELECT * FROM Person.Contact
在資料指標名稱關聯於資料指標之後,直到取消配置這個資料指標之前,相同範圍 (GLOBAL 或 LOCAL) 的其他資料指標不能使用這個名稱。
資料指標變數會利用兩種方法之一來關聯於資料指標:
-
依名稱,利用 SET 陳述式將資料指標設為資料指標變數。
DECLARE @MyCrsrRef CURSOR SET @MyCrsrRef = abc
-
不需要定義資料指標名稱,也可以建立資料指標,以及將資料指標關聯於變數。
DECLARE @MyCursor CURSOR SET @MyCursor = CURSOR LOCAL SCROLL FOR SELECT * FROM Person.Contact
DEALLOCATE @cursor_variable_name 陳述式只會移除資料指標的具名變數參考。在到了批次、預存程序或觸發程序結束而離開範圍之前,變數並不會取消配置。在 DEALLOCATE @cursor_variable_name 陳述式之後,您可以利用 SET 陳述式,將變數關聯於另一個資料指標。
USE AdventureWorks GO DECLARE @MyCursor CURSOR SET @MyCursor = CURSOR LOCAL SCROLL FOR SELECT * FROM Sales.SalesPerson DEALLOCATE @MyCursor SET @MyCursor = CURSOR LOCAL SCROLL FOR SELECT * FROM Sales.SalesTerritory GO
您不需要明確取消配置資料指標變數。當變數離開範圍時,會隱含地取消配置。
這個指令碼會顯示資料指標如何保存,直到最後一個名稱或參考這些資料指標的變數取消配置為止。
USE AdventureWorks GO -- Create and open a global named cursor that -- is visible outside the batch. DECLARE abc CURSOR GLOBAL SCROLL FOR SELECT * FROM Sales.SalesPerson 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 Sales.SalesTerritory -- The following statement deallocates the cursor -- because no other variables reference it. DEALLOCATE @MyCursor GO
社群新增項目
新增
顯示:

