SQLServer 游标 (A)

游标

游标分为客户端游标和服务器端游标。Sql通过游标可以对一个结果集进行逐行处理。对于使用服务器端游标的过程有:声明打开读取关闭释放。

1 声明游标

1.1 SQL92标准的声明

Declare cursor_name [insensitive][scroll] cursor

For select_statement

[for { readonly|update [of column_name[,…n]]}]

Insensitive:使用查询结果的副本

如:

declare xs_cur1 cursor

for

       select* from xs

       where stu_major='计算机'

for read only

1.2 T-SQL扩展的游标声明

Declare cursor_name Cursor

[local | global]                                      /*游标作用域*/

[forward_only | scroll]                        /*游标移动方向*/

[static| keyset | dynamic | fast_forward]   /*游标类型*/

[read_only | scroll_locks | optimistic]   /*访问属性*/

[tupe_warning]                               /*类型转换警告信息*/

For select_statement                                       

[for update [of column_name[,…n]]     /*可修改的列*/

Static:静态游标,只读

Keyset:键集驱动游标,可以通过键集驱动游标修改基本表中非关键字列的值。

dynamic :动态游标

fast_forward:只进游标

declare xs_cur2 cursor

dynamic

for

       select* from xs

       where stu_major='计算机'

 

2 打开游标

Open {{[global] cursor_name}| cursor_variable_name}

例子:/*定义游标,然后打开,输出其行数*/

declare xs_cur3 cursor

local scroll scroll_locks

for

select stu_id,stu_name,stu_total_credit    from xs

for update of stu_total_credit

open xs_cur3

select 'the number of rows'=@@cursor_rows

3 读取数据

游标打开后,就可以使用fetch语句从中读取数据。Fetch语句的格式为:

Fetch

[next|prior|first|last|absolute{n|@nvar}|relative{n|@nvar}]

From {{[global] cursor_name}| cursor_variable_name}

Into @variable_name[,….n]

如:fetch first from xs_cur2

注意:fetch语句执行的状态保存在全局变量@@Fetch_status中,其值为0,表示执行成功;为-1,表示所要读取的行不在结果集中;为-2,表示被提取的行已经不在(已被删除)。

4 关闭游标

Close  {{[global] cursor_name}| cursor_variable_name}

5 释放游标

Deallocate {{[global] cursor_name}| cursor_variable_name}

 

posted @ 2014-04-10 13:23  Gavin Liu  阅读(367)  评论(0编辑  收藏  举报

Right people get the right information at the right time.
以技术求生存,以市场求发展;学以至用,开拓创新;达技术之颠峰,至市场之广阔!