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)执行后的查询结果:

  • 相关阅读:
    Ubuntu创建VLAN接口配置
    Ubuntu配置网桥方法
    Ubuntu重启网卡的三种方法
    kvm存储池和存储卷
    ubuntu如何切换到root用户
    修改Ubuntu默认apt下载源
    Java之泛型<T> T与T的用法(转载)
    Java关键字(一)——instanceof(转载)-BeanCopier相关
    java代码之美(12)---CollectionUtils工具类(转载)
    Lombok-注解@Slf4j的使用
  • 原文地址:https://www.cnblogs.com/yuan-jun/p/7806755.html
Copyright © 2011-2022 走看看