遊標的使用

遊標主要用於存儲過程和觸發器中:
1.聲明變量,用於包含遊標返回的數據
2. 使用遊標聲明語句(declare cursor) 將遊標與select 語句關聯;
3. 使用open語句執行select語句並填充遊標;
4. 使用fetch into 語句提取單個行,並將其保存到指定變量中;
5. 使用close 語句關閉遊標(此時重新open仍然可以使用),或者使用deallocate  釋放遊標資源(要重新使用必須重新declare)
(1)遊標聲明語句
ISO Syntax
DECLARE cursor_name [ INSENSITIVE ] [ SCROLL ] CURSOR 
     FOR select_statement 
     [ FOR { READ ONLY | UPDATE [ OF column_name [ ,...n ] ] } ]
[;]
Transact-SQL Extended Syntax
DECLARE cursor_name CURSOR [ LOCAL | GLOBAL ] 
     [ FORWARD_ONLY | SCROLL ] 
     [ STATIC | KEYSET | DYNAMIC | FAST_FORWARD ] 
     [ READ_ONLY | SCROLL_LOCKS | OPTIMISTIC ] 
     [ TYPE_WARNING ] 
     FOR select_statement 
     [ FOR UPDATE [ OF column_name [ ,...n ] ] ]
[;]
example:
SET NOCOUNT ON;

DECLARE @vendor_id int, @vendor_name nvarchar(50),
    @message varchar(80), @product nvarchar(50);

PRINT '-------- Vendor Products Report --------';

DECLARE vendor_cursor CURSOR FOR 
SELECT VendorID, Name
FROM Purchasing.Vendor
WHERE PreferredVendorStatus = 1
ORDER BY VendorID;

OPEN vendor_cursor

FETCH NEXT FROM vendor_cursor 
INTO @vendor_id, @vendor_name

WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT ' '
    SELECT @message = '----- Products From Vendor: ' + 
        @vendor_name

    PRINT @message

    -- Declare an inner cursor based   
    -- on vendor_id from the outer cursor.

    DECLARE product_cursor CURSOR FOR 
    SELECT v.Name
    FROM Purchasing.ProductVendor pv, Production.Product v
    WHERE pv.ProductID = v.ProductID AND
    pv.VendorID = @vendor_id  -- Variable value from the outer cursor

    OPEN product_cursor
    FETCH NEXT FROM product_cursor INTO @product

    IF @@FETCH_STATUS <> 0 
        PRINT '         <<None>>'     

    WHILE @@FETCH_STATUS = 0
    BEGIN

        SELECT @message = '         ' + @product
        PRINT @message
        FETCH NEXT FROM product_cursor INTO @product
        END

    CLOSE product_cursor
    DEALLOCATE product_cursor
        -- Get the next vendor.
    FETCH NEXT FROM vendor_cursor 
    INTO @vendor_id, @vendor_name
END 
CLOSE vendor_cursor;
DEALLOCATE vendor_cursor;
(2)對於可更新遊標
可以通過where  current  of cursor_name  來進行定位
declare  OrderHeaderCursor   scroll cursor 
for
select SalesOrderID, OrderDate,SubTotal
from Sales.SalesOrderHeader
where  SalesOrderID > 75118
order by SalesOrderID
for update
open OrderHeaderCursor
fetch first from OrderHeaderCursor
update Sales.SalesOrderHeader
set SubTotal = 189.96
where current of OrderHeaderCursor
close OrderHeaderCursor
deallocate OrderHeaderCursor
(3) 滾動遊標
在cursor前加上關鍵字scroll,就可以出創建滾動遊標了,
 對於fetch語句,除了next外,還可以使用其他
FETCH 
          [ [ NEXT | PRIOR | FIRST | LAST 
                    | ABSOLUTE { n | @nvar } 
                    | RELATIVE { n | @nvar } 
               ] 
               FROM 
          ] 
{ { [ GLOBAL ] cursor_name } | @cursor_variable_name } 
[ INTO @variable_name [ ,...n ] ] 
NEXT

Returns the result row immediately following the current row and increments the current row to the row returned. If FETCH NEXT is the first fetch against a cursor, it returns the first row in the result set. NEXT is the default cursor fetch option.

PRIOR

Returns the result row immediately preceding the current row, and decrements the current row to the row returned. If FETCH PRIOR is the first fetch against a cursor, no row is returned and the cursor is left positioned before the first row.

FIRST

Returns the first row in the cursor and makes it the current row.

LAST

Returns the last row in the cursor and makes it the current row.

ABSOLUTE { | @nvar}

If n or @nvar is positive, returns the row n rows from the front of the cursor and makes the returned row the new current row. If n or @nvaris negative, returns the row n rows before the end of the cursor and makes the returned row the new current row. If n or @nvar is 0, no rows are returned. n must be an integer constant and @nvar must be smallint, tinyint, or int.

RELATIVE { | @nvar}

If n or @nvar is positive, returns the row n rows beyond the current row and makes the returned row the new current row. If n or @nvar is negative, returns the row n rows prior to the current row and makes the returned row the new current row. If n or @nvar is 0, returns the current row. If FETCH RELATIVE is specified with n or @nvar set to negative numbers or 0 on the first fetch done against a cursor, no rows are returned. n must be an integer constant and @nvar must be smallint, tinyint, or int.

GLOBAL

Specifies that cursor_name refers to a global cursor.

cursor_name

Is the name of the open cursor from which the fetch should be made. If both a global and a local cursor exist with cursor_name as their name, cursor_name to the global cursor if GLOBAL is specified and to the local cursor if GLOBAL is not specified.

@cursor_variable_name 

Is the name of a cursor variable referencing the open cursor from which the fetch should be made.

INTO @variable_name[ ,...n]

Allows data from the columns of a fetch to be placed into local variables. Each variable in the list, from left to right, is associated with the corresponding column in the cursor result set. The data type of each variable must either match or be a supported implicit conversion of the data type of the corresponding result set column. The number of variables must match the number of columns in the cursor select list.


(4)聲明遊標變量

declare   @OrderHeaderCursor   cursor   -- 聲明遊標變量
set @OrderHeaderCursor =   cursor  scroll  -- 爲遊標賦值
for
select SalesOrderID, OrderDate,SubTotal
from Sales.SalesOrderHeader
where  SalesOrderID > 75118
order by SalesOrderID
for update
open @OrderHeaderCursor  --打開遊標
fetch last from @OrderHeaderCursor  -- 使用遊標
update Sales.SalesOrderHeader
set SubTotal = 20.89
where current of @OrderHeaderCursor
close @OrderHeaderCursor   -- 關閉遊標
deallocate @OrderHeaderCursor  --釋放資源
發佈了20 篇原創文章 · 獲贊 370 · 訪問量 24萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章