SQL Server游标的基本用法
SQL Server游标的基本用法2011年03月01日
sql server中使用游标的基本步骤:
1、创建游标,语法:DECLARE CursorName CURSOR FOR SQL
2、打开游标,语法:open CursorName
3、操作游标(移动游标):语法:fetch next from myCursorCats into variable1[,variable2,variable3...];
判断全局变量@@fetch_status的值(int类型),如果为0表示语句成功(存在结果);如果为-1表示FETCH 语句失败或此行不在结果集中;如果为-2表示被提取的行不存在。 注:@@fetch_status值的改变是通过fetch next from实现的(FETCH NEXT FROM Cursor)
4、关闭游标,语法:CLOSE CursorName;DEALLOCATE CursorName
--示例代码
DECLARE @id varchar(20),@name nvarchar(50);
--创建游标
DECLARE myCursor CURSOR FOR select , from users where sex='男';
open myCursor;--打开游标
--循环移动游标
fetch next from myCursor into @id,@name;
while @@fetch_status=0
begin
select @id,@name;
fetch next from myCursor into @id,@name;
end
--关闭游标
CLOSE myCursor;
DEALLOCATE myCursor;
页:
[1]