一、简单静态游标示例:
代码
DECLARE product_cursor CURSOR STATIC FOR
SELECT cName FROM Product
OPEN product_cursor
FETCH NEXT FROM product_cursor INTO @product
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @message = ' ' + @product
PRINT @message
FETCH NEXT FROM product_cursor INTO @product
END
CLOSE product_cursor
DEALLOCATE product_cursor
SELECT cName FROM Product
OPEN product_cursor
FETCH NEXT FROM product_cursor INTO @product
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @message = ' ' + @product
PRINT @message
FETCH NEXT FROM product_cursor INTO @product
END
CLOSE product_cursor
DEALLOCATE product_cursor
二、静态游标与动态游标的区别
静态(STATIC)游标创建将由该游标使用的数据的临时复本。对游标的所有请求都从tempdb 中的这一临时表中得到应答;因此,在对该游标进行提取操作时返回的数据中不反映对基表所做的修改,并且该游标不允许修改
动态(DYNAMIC) 游标会反映在滚动游标时对结果集内的各行所做的所有数据更改。行的数据值、顺序和成员身份在每次提取时都会更改。动态游标不支持ABSOLUTE 提取选项。
FORWARD_ONLY
指定資料指標只能從第一個資料列捲到最後一個資料列。FETCH NEXT 是唯一支援的提取選項。若指定 FORWARD_ONLY 時未加上 STATIC、KEYSET 或 DYNAMIC 等關鍵字,資料指標便會作為 DYNAMIC 資料指標操作。沒有指定 FORWARD_ONLY 及 SCROLL 時,則預設為 FORWARD_ONLY,除非指定了 STATIC、KEYSET 或 DYNAMIC 關鍵字。
如果很在意游标的类型, 应该在定义游标的时候, 加上游标类型定义的关键字, 并加上TYPE_WARNING 关键字, 以便在游标类型不是预期的情况下, 收到警告信息
代码
--下面的演示针对 STATIC 和DYNAMIC 游标, 显示两者在游标循环期的差异
[code=SQL]
-- 定义演示数据
IF OBJECT_ID('tempdb..#tb') IS NOT NULL
DROP TABLE #tb
CREATE TABLE #tb(
id int PRIMARY KEY,
col sysname)
INSERT #tb(
id, col)
SELECT 1, 'AA' UNION ALL
SELECT 2, 'BB' UNION ALL
SELECT 3, 'CC' UNION ALL
SELECT 4, 'DD'
-- 游标测试
DECLARE CUR_tb CURSOR LOCAL FORWARD_ONLY READ_ONLY TYPE_WARNING STATIC --DYNAMIC
FOR
SELECT
id, col
FROM #tb
-- 游标打开前删除记录
DELETE TOP (1)
FROM #tb
WHERE id = 4
SELECT 'before cursor open', * FROM #tb
-- 打开游标
OPEN CUR_tb
-- 游标打开后删除记录
DELETE TOP (1)
FROM #tb
WHERE id = 3
SELECT 'after cursor open', * FROM #tb
FETCH CUR_tb
WHILE @@FETCH_STATUS = 0
BEGIN
-- 游标循环中删除记录
DELETE TOP (1)
FROM #tb
WHERE id = 2
FETCH CUR_tb
END
CLOSE CUR_tb
DEALLOCATE CUR_tb
[code=SQL]
-- 定义演示数据
IF OBJECT_ID('tempdb..#tb') IS NOT NULL
DROP TABLE #tb
CREATE TABLE #tb(
id int PRIMARY KEY,
col sysname)
INSERT #tb(
id, col)
SELECT 1, 'AA' UNION ALL
SELECT 2, 'BB' UNION ALL
SELECT 3, 'CC' UNION ALL
SELECT 4, 'DD'
-- 游标测试
DECLARE CUR_tb CURSOR LOCAL FORWARD_ONLY READ_ONLY TYPE_WARNING STATIC --DYNAMIC
FOR
SELECT
id, col
FROM #tb
-- 游标打开前删除记录
DELETE TOP (1)
FROM #tb
WHERE id = 4
SELECT 'before cursor open', * FROM #tb
-- 打开游标
OPEN CUR_tb
-- 游标打开后删除记录
DELETE TOP (1)
FROM #tb
WHERE id = 3
SELECT 'after cursor open', * FROM #tb
FETCH CUR_tb
WHILE @@FETCH_STATUS = 0
BEGIN
-- 游标循环中删除记录
DELETE TOP (1)
FROM #tb
WHERE id = 2
FETCH CUR_tb
END
CLOSE CUR_tb
DEALLOCATE CUR_tb