使用游标有四种基本的步骤:声明游标、打开游标、提取数据、关闭游标。
如下面SQL示例所示:
--
=============================================
-- Author: <搏击的小船>
-- Create date: <2011-04-19>
-- Description: <SQL SERVER 游标DEMO>
-- =============================================
-- 临时表
CREATE TABLE ##TempTB
(
ID INT IDENTITY ,
ColA VARCHAR ( 50 ),
ColB VARCHAR ( 50 )
)
DECLARE @i INT = 0 ;
WHILE ( @i < 10 )
BEGIN
INSERT INTO ##TempTB
(ColA, ColB )
VALUES (
' 测试字段ColA ' + CAST ( @i AS VARCHAR ( 10 ))
,
' 测试字段ColB ' + CAST ( @i AS VARCHAR ( 10 ))
)
SET @i = @i + 1 ;
END
--SELECT * FROM ##TempTB;
-- 定义3个变量来接收游标遍历的值
DECLARE @a VARCHAR ( 50 ),
@b VARCHAR ( 50 ),
@c VARCHAR ( 50 );
-- 申明游标并填充数据
DECLARE cur CURSOR FOR SELECT * FROM ##TempTB
-- 打开游标
OPEN cur
-- 取下一条数据填充
FETCH NEXT FROM cur INTO @a , @b , @c
SELECT @a , @b , @c ;
-- @@FETCH_STATUS | 0 提取成功; 1语句失败或行不在结果集中;2提取的行不存在
WHILE ( @@FETCH_STATUS = 0 )
BEGIN
-- to do sth//
FETCH NEXT FROM cur INTO @a , @b , @c ;
SELECT @a , @b , @c ;
END
-- 关闭游标
CLOSE cur
-- 删除游标资源
DEALLOCATE cur
DROP TABLE ##TempTB;
-- Author: <搏击的小船>
-- Create date: <2011-04-19>
-- Description: <SQL SERVER 游标DEMO>
-- =============================================
-- 临时表
CREATE TABLE ##TempTB
(
ID INT IDENTITY ,
ColA VARCHAR ( 50 ),
ColB VARCHAR ( 50 )
)
DECLARE @i INT = 0 ;
WHILE ( @i < 10 )
BEGIN
INSERT INTO ##TempTB
(ColA, ColB )
VALUES (
' 测试字段ColA ' + CAST ( @i AS VARCHAR ( 10 ))
,
' 测试字段ColB ' + CAST ( @i AS VARCHAR ( 10 ))
)
SET @i = @i + 1 ;
END
--SELECT * FROM ##TempTB;
-- 定义3个变量来接收游标遍历的值
DECLARE @a VARCHAR ( 50 ),
@b VARCHAR ( 50 ),
@c VARCHAR ( 50 );
-- 申明游标并填充数据
DECLARE cur CURSOR FOR SELECT * FROM ##TempTB
-- 打开游标
OPEN cur
-- 取下一条数据填充
FETCH NEXT FROM cur INTO @a , @b , @c
SELECT @a , @b , @c ;
-- @@FETCH_STATUS | 0 提取成功; 1语句失败或行不在结果集中;2提取的行不存在
WHILE ( @@FETCH_STATUS = 0 )
BEGIN
-- to do sth//
FETCH NEXT FROM cur INTO @a , @b , @c ;
SELECT @a , @b , @c ;
END
-- 关闭游标
CLOSE cur
-- 删除游标资源
DEALLOCATE cur
DROP TABLE ##TempTB;