1、普通循環執行SQL
declare @i int --聲明 set @i=1 --初始化 while @i<=50 --執行條件 begin exec [dbo].[LineCalendar] @lineId= @i --執行的SQL set @i=@i+1 --執行后變量加1 end
使用游標的順序: 聲名游標、打開游標、讀取數據、關閉游標、刪除游標。
2、游標循環(沒有事務)
---游標循環遍歷-- 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 --判斷游標的狀態 --0 fetch語句成功 --1 fetch語句失敗或此行不在結果集中 --2 被提取的行不存在 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
3、游標循環(事務)
---游標循環遍歷-- 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
原文:https://www.cnblogs.com/xielong/p/5941595.html