標籤:rollback 修改 查看 from date 死迴圈 學生 into ror
1、首先需要一個測試表資料Student
2、普通迴圈
1)迴圈5次來修改學生表資訊
--迴圈遍曆修改記錄--
declare @i int
set @i=0
while @i<5
begin
update Student set demo = @i+5 where [email protected]
set @[email protected] +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 [email protected],[email protected] where [email protected]
set @[email protected]+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 [email protected],[email protected] where [email protected]
set @[email protected]+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迴圈遍曆(普通迴圈和遊標迴圈)