1. 程式人生 > >SQL SERVER循環遍歷(普通循環和遊標循環)

SQL SERVER循環遍歷(普通循環和遊標循環)

into 變量 alloc lar -1 記錄 gin pda 普通

1、首先需要一個測試表數據Student

技術分享

2、普通循環

1)循環5次來修改學生表信息

--循環遍歷修改記錄--
declare @i int
set @i=0
while @i<5
begin
update Student set demo = @i+5 where Uid=@i
set @i=@i +1
end
--查看結果--
select * from Student

2)執行後的查詢結果

技術分享

3、遊標循環(沒有事務)

1)根據學生表實際數據循環修改信息
---遊標循環遍歷--
begin
declare @a int,@error int
declare @temp varchar(50)

set @a=1
set @error=0
--申明遊標為Uid
declare order_cursor cursor
for (select [Uid] from Student)
--打開遊標--
open order_cursor
--開始循環遊標變量--
fetch next from order_cursor into @temp
while @@FETCH_STATUS = 0 --返回被 FETCH語句執行的最後遊標的狀態--
begin
update Student set Age=15+@a,demo=@a where Uid=@temp
set @a=@a+1
set @error= @error + @@ERROR --記錄每次運行sql後是否正確,0正確
fetch next from order_cursor into @temp --轉到下一個遊標,沒有會死循環
end
close order_cursor --關閉遊標
deallocate order_cursor --釋放遊標
end
go
--查看結果--
select * from Student

2)執行後的查詢結果

技術分享

4、遊標循環(事務)

1)根據實際循環學生表信息

---遊標循環遍歷--
begin
declare @a int,@error int
declare @temp varchar(50)
set @a=1
set @error=0
begin tran --申明事務
--申明遊標為Uid
declare order_cursor cursor
for (select [Uid] from Student)
--打開遊標--
open order_cursor
--開始循環遊標變量--
fetch next from order_cursor into @temp
while @@FETCH_STATUS = 0 --返回被 FETCH語句執行的最後遊標的狀態--
begin
update Student set Age=20+@a,demo=@a where Uid=@temp
set @a=@a+1
set @error= @error + @@ERROR --記錄每次運行sql後是否正確,0正確
fetch next from order_cursor into @temp --轉到下一個遊標
end
if @error=0
begin
commit tran --提交事務
end
else
begin
rollback tran --回滾事務
end
close order_cursor --關閉遊標
deallocate order_cursor --釋放遊標
end
go
--查看結果--
select * from Student

2)執行後的查詢結果:

技術分享

SQL SERVER循環遍歷(普通循環和遊標循環)