游标:游标实际上是一种能从包括多条数据记录的结果集中每次提取一条记录的机制
游标把作为面向集合的数据库管理系统和面向行的程序设计两者联系起来,使两个数据处理方式能够进行沟通
游标种类:
由DECLARE CURSOR 语法定义主要用在Transact_SQL 脚本,存储过程和触发器中
支持在OLE DB ODBC 以及DB_library 中使用游标函数,主要用在服务器上。
主要是当在客户机上缓存结果集时才使用
使用游标:
声明游标;
declare cursor_name
[insensitive] [scroll] cursor for select_statement [for {read only | update [ of column_name [ ,...n] ] }]
打开游标
open {cursor_name | cursor_variable_name}
提取数据
FETCH [ [ NEXT | PRIOR | FIRST | LAST
| ABSOLUTE { n | @nvar }
| RELATIVE { n | @nvar }
]
FROM
]
{ cursor_name | @cursor_variable_name }
[ INTO @variable_name [,...n ] ]
使用@@FETCH_STATUS全局变量判断数据提取状态
返回值是“0”表示FETCH语句成功,”-1“表示失败或此行不在结果中。”-2“表示被提取的行不存在
关闭游标:
CLOSE { cursor_name |
cursor_variable_name }
DEALLOCATE { cursor_name | cursor_variable_name }
释放游标就释放了与该游标有关的一切资源,包括游标的声明,以后就不能再使用OPEN语句打开此游标了
使用set语句将游标复制给游标变量
declare @cui_ta cursor /*声明游标变量*/
declare sc_curscroll cursor /*声明游标*/
for
select * from sc
set @cui_ta = sc_curscroll /*赋值*/
例子1:从学生表(student)中,声明一个姓”易“的学生的游标
declare sname_cursor cursor for
select sname from student
where sname like '易%'
order by sname
open sname_cursor
/*提取第一行数据*/
fetch next from sname_cursor
while @@fetch_status = 0
begin
.......处理从游标中提取的数据
fetch next from sname_cursor
end
close sname_cursor
deallocate sname_cursor
go
例二:
declare @sname char(10),@sgrade smallint
declare stu_cursor cursor for
select sname,sno from student
open stu_cursor
fetch next from stu_cursor into @sname,@sgrade
while @@fetch_status = 0
begin
print 'sname:'+@sname+' sgrade'+cast(@sgrade as varchar(4))
fetch next from stu_cursor into @sname,@sgrade
end
close stu_cursor
deallocate stu_cursor
go