T-SQL 中游标应用示例

作者:leen 来源:ITPOW(原创) 日期:2006-10-25
declare cr cursor for select docTitle, author from tblDocs --第 1 句
open cr --第 2 句

declare @docTitle varchar(50), @author varchar(20) --第 3 句
fetch next from cr into @docTitle, @author --第 4 句
while @@fetch_status=0 --第 5 句
begin
    print @docTitle + ' 的作者是 ' + @author --第 6 句
    fetch next from cr into @docTitle, @author --第 7 句
end

close cr --第 8 句
deallocate cr --第 9 句

在查询分析器中,以上代码将表 tblDocs 中的 docTitle, author 以特定的形式显示出来。

第 1 句 declare 申明游标,注意不像其它变量一样,变量名没有以 @ 开头,for 之后为 sql 语句。

第 2 句打开游标。

与第 1、2 句对应的第 8、9 句分别表示 关闭游标,释放对象。可以按 RecordSet 对象来理解。

第 4 句是将值赋予变量,其格式为:fetch next from 游标名 into 变量序列

第 5 句的 @@fetch_status 是一个全局变量,当其值为 0 时,表示取值成功。

相关文章