今天突然接触到游标,突然发现并没有想象中的那么难。如果你也是刚学习的,那对你应该很有帮助的。
使用游标,分为以下几步:
1. 定义游标(包括游标的集合)
2. 打开游标
3. 遍历游标 (一行行的读取游标集合的记录)
4. 关闭游标
5. 释放游标
游标使用范例:
declare @ Id int ;declare @ StudentName nvarchar ( 100 );declare StudentCursor Cursor for --定义游标select Id , Name --游标的集合from dbo . T_Student ;open StudentCursor ; --打开游标-- Check @@FETCH_STATUS to see if there are any more rows to fetch.fetch next from StudentCursor into @ Id , @ StudentName ; --游标移动到下一行,并将值存入变量(变量的顺序必须与游标查询结果顺序一致)while ( @@ FETCH_STATUS = 0 ) --@@FETCH_STATUS 0:FETCH 语句成功;1:FETCH 语句失败或行不在结果集中;begin --2:提取的行不存在;print ( @ Id + ':' +@ StudentName );-- This is executed as long as the previous fetch succeeds.fetch next from StudentCursor into @ Id , @ StudentName ; --游标移动到下一行endclose StudentCursor ; --关闭游标deallocate StudentCursor ; --释放游标如果你想知道游标更详细信息,请参考MSDN信息: