游标分为客户端游标和服务器端游标。Sql通过游标可以对一个结果集进行逐行处理。对于使用服务器端游标的过程有:声明、打开、读取、关闭、释放。
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
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=‘计算机‘
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
游标打开后,就可以使用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,表示被提取的行已经不在(已被删除)。
Close {{[global] cursor_name}| cursor_variable_name}
Deallocate {{[global] cursor_name}| cursor_variable_name}
SQLServer 游标 (A),布布扣,bubuko.com
原文:http://www.cnblogs.com/llbofchina/p/3656286.html