游标分为客户端游标和服务器端游标。Sql经过游标能够对一个结果集进行逐行处理。对于使用服务器端游标的过程有:声明、打开、读取、关闭、释放。服务器
Declare cursor_name [insensitive][scroll] cursorfetch
For select_statementspa
[for { readonly|update [of column_name[,…n]]}]作用域
Insensitive:使用查询结果的副本it
如:io
declare xs_cur1 cursorast
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}