declare cursor_text cursor SCROLL for select memo from dbo.backmemo --DECLARE 定义游标,对于未指定SCROLL选项的游标来说,只支持NEXT取值.
open cursor_text --打开游标
declare @row varchar(100) --定义变量
--只有支持6种移动选项,分别为到第一行(FIRST),最后一行(LAST),下一行(NEXT),上一行(PRIOR),直接跳到某行(ABSOLUTE(n)),相对于目前跳几行(RELATIVE(n))
--把游标赋值给变量(注意:这里上面的查询语句,查出来几列,就需要几个变量去接收值)
fetch next from cursor_text into @row --下一行
print @row
fetch first from cursor_text into @row --第一行
print @row
fetch prior from cursor_text into @row --上一行
print @row
fetch ABSOLUTE 4 from cursor_text into @row --取第四行
print @row
fetch RELATIVE -1 from cursor_text into @row --当前行的上一行
print @row
close cursor_text --关闭游标
deallocate cursor_text --当游标不再需要被使用后,释放游标
-- 游标经常会和全局变量@@FETCH_STATUS与WHILE循环来共同使用,以达到遍历游标所在数据集的目的,例如:
declare text_cursor cursor scroll for select item_clsno,item_clsname from bi_t_item_cls
open text_cursor
declare @item_code varchar(50)
declare @item_name varchar(60)
while @@FETCH_STATUS=0
begin
fetch next from text_cursor into @item_code,@item_name
print @item_code
print @item_name
end
close text_cursor
deallocate text_cursor
转载于:https://blog.51cto.com/317057112/1165474