--建立測試臨時表
if(object_id('tempdb..#books') is not null)
begin
drop table #books;
endcreate table #books
(bookname nvarchar(20),
bookcode nvarchar(20)
)insert into #books( bookname, bookcode ) values(n'c# 本質論','jc556874');
insert into #books( bookname, bookcode ) values(n'js 本質論','js556874');
--申明乙個游標
declare mycursor cursor for
select top 5 bookname,bookcode from #books;
--開啟乙個游標
open mycursor;
declare @bookname nvarchar(20);
declare @bookcode nvarchar(20);
--迴圈乙個游標
fetch next from mycursor into @bookname,@bookcode;
while(@@fetch_status = 0)
begin
print('book name: '+@bookname);
fetch next from mycursor into @bookname,@bookcode;
end
--關閉游標
close mycursor;
--釋放資源
deallocate mycursor;
@@fetch_status 是乙個全域性變數,其值有以下三種 :
1) 0 fetch 語句成功
2) -1 fetch 語句失敗或此行不在結果集中
3) -2 被提取的行不存在
SQL游標示例
declare userid char 6 declare username varchar 20 declare email varchar 200 declare testcur cursor for select userid,username,email from tbusercommon ...
SQL 游標示例
1 declare iint 2declare teststr varchar 50 3 set i 0 給初始值45 create table temp test 建立臨時表6 7 num varchar 50 8 9while i 10 10begin 11insert into temp te...
Sqlserver 游標簡單示例
建立乙個游標 declare my cursor cursor for my cursor為游標的名稱,隨便起 select id,name from my user 這是游標my cursor的值,這裡隨便發揮看業務場景 開啟游標 open my cursor 沒什麼好說的 變數 declare ...