SQL Server循環
阿新 • • 發佈:2018-08-21
div back pre order spa server html lba 釋放
1.普通循環
1 DECLARE @i int 2 3 set @i=0 4 while @i<5 5 BEGIN 6 update Student set demo = demo+5 WHERE Uid=@i 7 set @i=@i +1 8 --PRINT @i 9 END
2.遊標循環(沒有事務)
1 ---遊標循環(沒有事務) 2 3 BEGIN 4 DECLARE @a INT,@error INT 5 DECLARE @temp NVARCHAR(50) 6 SET @a=1 7 SET @error=0 8 -----申明遊標為uid 9 DECLARE order_cursor CURSOR 10 FOR (SELECT [Uid] FROM Student) 11 -----打開遊標 12 OPEN order_cursor 13 ---- 開始循環遊標變量 14 FETCH NEXT FROM order_cursor INTO @temp 15 16 WHILE @@FETCH_STATUS=0 -----返回被FETCH語句執行的最後遊標的狀態 17 BEGIN18 UPDATE student SET Age=15+@a,demo=@a WHERE uid=@temp 19 SET @a=@a+1 20 SET @error=@error+@@ERROR ------記錄每次運行sql後是否正確 0正確 21 FETCH NEXT FROM order_cursor INTO @temp -----轉到下一個遊標,沒有會死循環 22 END 23 CLOSE order_cursor ----關閉遊標 24 DEALLOCATE order_cursor ---釋放遊標 25 END
3.遊標循環(含事務)
1 ---遊標循環遍歷-- 2 BEGIN 3 DECLARE @a INT ,@error INT 4 DECLARE @temp VARCHAR(50) 5 SET @a=1 6 SET @error=0 7 BEGIN TRAN 8 DECLARE order_cursor CURSOR 9 FOR(SELECT uid FROM student) 10 OPEN order_cursor 11 FETCH NEXT FROM order_cursor INTO @temp 12 WHILE @@FETCH_STATUS=0 ---返回被fetch語句執行的最後遊標的狀態 13 BEGIN 14 UPDATE student SET age=40+@a,demo=@a WHERE uid=@temp 15 SET @a=@a+1 16 SET @error=@error+@@ERROR 17 FETCH NEXT FROM order_cursor INTO @temp ----轉到下一個遊標 18 END 19 IF(@error=0) 20 BEGIN 21 COMMIT TRAN 22 END 23 ELSE 24 BEGIN 25 ROLLBACK TRAN 26 END 27 CLOSE order_cursor 28 DEALLOCATE order_cursor 29 END
轉載
https://www.cnblogs.com/onroad2016/p/8650572.html
SQL Server循環