--下例为 authors 表中所有的姓声明了一个简单的游标,并使用 FETCH NEXT 逐个提取这些行。FETCH 语句以单行结果集形式返回由 DECLARE CURSOR 指定的列的值。
USE pubs
GO
DECLARE authors_cursor INSENSITIVE CURSOR FOR
SELECT au_lname FROM authors
ORDER BY au_lname
print @@cursor_rows --当前游标没有打开,所以结果为0
OPEN authors_cursor --打开游标
print @@cursor_rows --已经有了结果。
print @@fetch_status --执行第一条fetch语句之前,@@fetch_status=-1,表示还没有结果。
FETCH NEXT FROM authors_cursor --执行第一条fetch语句
WHILE @@FETCH_STATUS = 0 --这时才可以检查@@fetch_status的值,=0表示成功,这里是一个循环
BEGIN
-- This is executed as long as the previous fetch succeeds.
FETCH NEXT FROM authors_cursor --这里的fetch语句被循环执行。
if @@fetch_status <> 0
print @@fetch_status
END
CLOSE authors_cursor --关闭游标
DEALLOCATE authors_cursor --释放游标
GO