游标平时不怎么用,以前学过印象也不深了,今天要用查查资料发现,这个跟我平时用临时表的区别大吗?好像不大。。可能是我理解不深刻吧。
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 --释放游标
返回结果:
Customer Number:CVN6653A | Customer Name:VINA KRAFT PAPER CO., LTD | Customer FName:VINA KRAFT PAPER CO., LTD Customer Number:CVN6652A | Customer Name:VIETNAM PAPER CORP | Customer FName:VIETNAM PAPER CORP Customer Number:CVN6648A | Customer Name:TUAN DUNG COMPANY LIMITED | Customer FName:TUAN DUNG COMPANY LIMITED Customer Number:CVN6645A | Customer Name:THAI DUONG INVESTMENT AND DEVELOPMENT JOINT STOCK COMPANY | Customer FName:THAI DUONG INVESTMENT AND DEVELOPMENT JOINT STOCK COMPANY Customer Number:CVN6623A | Customer Name:SAIGON MY XUAN PAPER CO., LTD | Customer FName:SAIGON MY XUAN PAPER CO., LTD Customer Number:CVN6616A | Customer Name:PULPPY CORELEX (VIET NAM) CO LTD | Customer FName:PULPPY CORELEX (VIET NAM) CO LTD Customer Number:CVN6583A | Customer Name:PHU AN PRODUCTION TRADING CO LTD | Customer FName:PHU AN PRODUCTION TRADING CO LTD Customer Number:CVN6568A | Customer Name:NAM MINH UNION CO.,LTD | Customer FName:NAM MINH UNION CO.,LTD Customer Number:CVN6552A | Customer Name:LAM AN TRADING COMPANY LTD | Customer FName:LAM AN TRADING COMPANY LTD Completion time: 2020-08-20T10:48:13.5712104+08:00