SQL随笔之游标的用法

sql中的游标,一般是用来对数据进行循环处理的,游标实际上是一种能从包括多条数据记录的结果集中每次提取一条记录的机制。游标充当指针的作用。尽管游标能遍历结果中的所有行,一次只指向一行。

游标的使用步骤:

   1、定义游标
   2、打开游标
   3、使用游标
   4、关闭游标
   5、释放游标

declare @temp1 int,@temp2 int--定义临时变量
declare 游标1 cursor for select 字段1,字段2,... fromwhere 查询条件--定义游标
open mycursor--打开游标
fetch next from mycursor into @temp1,@temp2--读取一行
while @@FETCH_STATUS=0
begin
    --执行增删改查逻辑
    fetch next from mycursor into @temp1,@temp2--读取下一行
end
Close  游标1                        --关闭游标 
Deallocate  游标1                    --删除游标

获取游标的数据
  FETCH [[NEXT | PRIOR | FIRST | LAST | 
  ABSOLUTE{ n | @nvar | RELATIVE { n | @nvar}]
  From ] 游标名 [into 变量]
  注:
    NEXT  下一行  PRIOR  上一行  FIRST 第一行
    LAST  最后一行  ABSOLUTE n 第n行
    RELATIVE n 当前位置开始的第n行
    into 变量 把当前行的各字段值赋值给变量

游标状态变量:
    @@fetch_status  游标状态
         0 成功  -1 失败  -2 丢失
    @@cursor_rows 游标中结果集中的行数
        n 行数 -1 游标是动态的  0 空集游标
操作游标的当前行:
   current of 游标名

 

例如我们可以更新或者删除当前行的数据:

declare @temp1 int,@temp2 int--定义临时变量
declare 游标1 cursor for select 字段1,字段2,... fromwhere 查询条件--定义游标
open mycursor--打开游标
fetch next from mycursor into @temp1,@temp2--读取一行
while @@FETCH_STATUS=0
begin
    --执行增删改查逻辑
    update 表2 set 字段1='' where current of  游标1 --修改游标中的当前行
    fetch next from mycursor into @temp1,@temp2--读取下一行
end
Close  游标1                        --关闭游标 
Deallocate  游标1                    --删除游标

 

posted on 2016-11-28 16:07  雨刚下过  阅读(194)  评论(0)    收藏  举报