zoukankan      html  css  js  c++  java
  • 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

      

  • 相关阅读:
    cookie和session会话技术
    hdoj 1176 免费馅饼
    nyoj 14 会场安排问题
    hdoj 1575 Tr A
    poj 1163 The Triangle
    hdoj 2157 How many ways??
    贪心Poj1328
    贪心 序列
    差分约束Poj 3169 Layout
    差分约束Poj3159 Candies
  • 原文地址:https://www.cnblogs.com/onroad2016/p/8650572.html
Copyright © 2011-2022 走看看