zoukankan      html  css  js  c++  java
  • SQL SERVER循环遍历(普通循环和游标循环)

    1、首先需要一个测试表数据Student

    2、普通循环

    1)循环5次来修改学生表信息

    --循环遍历修改记录--
    declare @i int   
    set @i=0
    while @i<5
    begin
        update Student set demo = @i+5 where Uid=@i
        set @i=@i +1 
    end
    --查看结果--
    select * from Student

    2)执行后的查询结果

    3、游标循环(没有事务)

    1)根据学生表实际数据循环修改信息
    ---游标循环遍历--
    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
        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
    --查看结果--
    select * from Student

    2)执行后的查询结果

    4、游标循环(事务)

    1)根据实际循环学生表信息

    ---游标循环遍历--
    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
    --查看结果--
    select * from Student

    2)执行后的查询结果:

  • 相关阅读:
    图解 PHP运行环境配置和开发环境的配置
    PHP学习笔记(2)语法和数据类型
    Jquery调用 新浪微博API 用户资料
    [转载]并行计算部分总结
    Qt QTreeWidget节点的添加+双击响应+删除详解
    C/C++中函数参数传递详解
    C语言预处理——宏定义
    cuda工程在VS中使用心得
    MPI用于矩阵乘积示例
    开到荼蘼花事了,永世相守孟婆桥
  • 原文地址:https://www.cnblogs.com/yuan-jun/p/7806755.html
Copyright © 2011-2022 走看看