• SQL Server循环


    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   BEGIN
    18   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

  • 相关阅读:
    PHP多条件模糊查询
    纯干货!一款APP从设计稿到切图过程全方位揭秘(转)
    0532. K-diff Pairs in an Array (M)
    0933. Number of Recent Calls (E)
    0139. Word Break (M)
    0713. Subarray Product Less Than K (M)
    0399. Evaluate Division (M)
    0495. Teemo Attacking (M)
    0179. Largest Number (M)
    0389. Find the Difference (E)
  • 原文地址:https://www.cnblogs.com/imstrive/p/9509400.html
Copyright © 2020-2023  润新知