1. 程式人生 > 實用技巧 >SQL Server中的遊標

SQL Server中的遊標

遊標平時不怎麼用,以前學過印象也不深了,今天要用查查資料發現,這個跟我平時用臨時表的區別大嗎?好像不大。。可能是我理解不深刻吧。

 1 use Test
 2 
 3 declare @cusnum varchar(10), @cusname Nvarchar(100),  @cusfname Nvarchar(100)--這邊用nvarchar因為有可能是中文。
 4 declare cusinfo cursor scroll --定義遊標 --scroll為滾動遊標
 5     for
 6     select top 10 cardcode, cardname, CardFName   
 7
from ocrd 8 where cardname is not null and cardcode like 'C%' 9 order by cardcode desc 10 open cusinfo -- 開啟遊標 11 fetch next from cusinfo INTO @cusnum, @cusname, @cusfname --抓取下一行遊標資料 12 while @@fetch_status=0 --0 FETCH 語句成功; -1 FETCH 語句失敗或此行不在結果集中; -2 被提取的行不存在 13 begin 14
print 'Customer Number:' + @cusnum +' | '+'Customer Name:' + @cusname +' | '+'Customer FName:' + @cusfname 15 fetch next from cusinfo into @cusnum, @cusname, @cusfname --抓取下一行遊標資料 16 end 17 close cusinfo --關閉遊標 18 deallocate cusinfo --釋放遊標