T-SQL之游标

1、声明游标

declare cursor_name CURSOR for select_statement(注意红色字体部分的顺序)

2打开游标

open cursor_name

打开游标后,就可以使用@@cursor_rows全局变量检索游标中的行数。

3、使用游标

FETCH next FROM cursor_name INTO @variable_name

4、关闭游标

close  cursor_name

5、释放游标

DEALLOCATE  cursor_name

一般都会使用while循环,记得在while循环中还要使用一次fetch next from cursor_name into @variable_name,

否则是死循环,若是有游标嵌套使用,则一定要记得把循环里的游标关闭后再进行外循环。

例如:

declare mycur1 CURSOR for select cno,avg(grade) from sc group by cno
open mycur1
declare @kcno char(10),@chji numeric(7,3)
fetch next from mycur1 into @kcno,@chji 
    --取当前指针记录并下移指针
while @@fetch_status=0  --判断的是刚刚指针取记录操作是否成功
  begin
     print case     --也可使用select
              when @chji>90 then @kcno+'号课程平均成绩优秀!'
              when @chji>80 then @kcno+'号课程平均成绩良好!'
              when @chji>70 then @kcno+'号课程平均成绩较好!'
              when @chji>60 then @kcno+'号课程平均成绩差!'
              else @kcno+'号课程平均成绩太差!'
            end
    fetch next  from mycur1 into @kcno,@chji
end
close mycur1

原文地址:https://www.cnblogs.com/mymindview/p/3451278.html