游标

用户可以逐行访问由SQL Server返回的结果集

使用游标的步骤

1,声明游标      使用T-SQL语句生成一个结果集

2,打开游标

3,从游标的结果集中读取数据

4,对游标中的数据逐行操作

5,关闭游标

声明游标

  declare  游标名  [scroll]  cursor  for  <select  语句>

    [for  read  only  |   update  of  列名]

 例如:

   declare  mycursor  cursor  for  select  *  from  addsalary

游标的两种类型

   有且只有两种类型:for  read  only  或 for  update   当游标方式指定为for read  only时,游标涉及表不能被修改

 指定为for  update时,可以删除或更新游标涉及的表中的行,通常缺省方式为 for  update方式

例如:

  declare  stu_cursor  cursor  for  select  sno,sname  from  student  where  dept='计算机'  for read  only

打开游标:

  open  游标名

注意:

 1,当游标打开成功时,游标位置指向结果集的第一行之前

 2,只能打开已经声明但未打开的游标

 3,当执行打开游标的语句时,服务器执行声明游标时,使用的select语句

读取游标

  fetch  [next|prior|first|last|absolute|relative]   from 游标名

  next:取下一行的数据,并把下一行作为当前行

  prior:返回紧临当行前面的结果行

  first:返回游标中的第一行并将其作为当前行

  last:返回游标中的最后一行并将其作为当前行

  absolute:当为正时,返回从游标头开始的第N行将返回的行变成新的当前行

  relative:当为正时,返回当前行之后的第N行将返回的行变成新的当前行

读取第一行数据

  fetch  next  from mycursor   如定义了scroll,则可用所有读取方式,如没有定义,只能用next读取

查看游标信息

  @@fetch_status  以确定是否还可以继续取数

      =0   成功    =-1,失败或此行不再结果集中  =-2,被提取的行不存在

 

流程:

    1,声明游标

     declare  authors_cur  cursor   for  select  an_lname,au_fname  from   authors   where  state=‘CA’  order by  an_lname

   2,打开一个游标

      open  authors_cur

   3,执行第一次取数操作

 fetch  next  from   authors_cur

   4,检查 @@fetch_status 以确定是否还可以继续取数

        where  @@fetch_status=0

        begin

                fetch  next  from  authors_cur

       end

    5,关闭游标

       close  authors_cur

  

使用游标修改数据

    update  表名(或视图名)    set  列名=修改后的值    where   current  of  游标名

   注:表名可省略,但必须是声明游标中的表名,且游标必须是已经打开的游标

例如:通过游标将学生表中第一条记录的姓名改名

    declare  cur_c  cursor  for   select  *  from  xs  for updte  of  sname

    open  cur_c

   fetch  next  from  cur_c  

   update  xs  set  sname='bbb'  where current of  cur_c

 close  cur_c

  deallocate   cur_c

使用游标删除数据

  delete  from 表名  where  current  of  游标名   ---用户删除游标当前位置所在行,删除或游标位置向前移动一行

 

posted @ 2017-02-03 14:38  Sealee  阅读(272)  评论(0编辑  收藏  举报