• sqlserver循环


    普通while循环

      1 循环5来修改学生信息

               循环遍历修改记录 

          DECLARE @i int 

        set @i=0
        while @i<5
        BEGIN
        update Student set demo = demo+5 WHERE Uid=@i
        set @i=@i +1
        --PRINT @i
        END

      2   游标循环(没有事务)

                   ----游标循环(没有事务)

        BEGIN
        DECLARE @a INT,@error INT
        DECLARE @temp NVARCHAR(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

    3    包含事务

      

    ---游标循环遍历--
    BEGIN
    DECLARE @a INT ,@error INT
    DECLARE @temp VARCHAR(50)
    SET @a=1
    SET @error=0
    BEGIN TRAN
    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=40+@a,demo=@a WHERE uid=@temp
    SET @a=@a+1
    SET @error=@error+@@ERROR
    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

    4  https://blog.csdn.net/lockepeak/article/details/2632904

      

  • 相关阅读:
    HDU_1242_Rescue
    HDU_1175_连连看
    HDU_1072_Nightmare
    HDU_2544_最短路
    POJ_2195_Going Home
    POJ_3565_Ants
    KM算法(Kuhn-Munkres)
    POJ_2536_Gopher II
    ODATA 云驱动 http://www.cdata.com/cloud/
    Wijmo 5 与Breeze 的组合,及与METRONIC 的集成
  • 原文地址:https://www.cnblogs.com/onroad2016/p/8650572.html
Copyright © 2020-2023  润新知