SQL SERVER遊標的使用

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

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章