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

  • 相关阅读:
    javascript设计模式小记
    静态iframe异步加载
    博客搬家分割线
    大数据学习之MapReduce篇
    IDEA 创建javaWeb以及Servlet
    数组定义 二维数组 数组遍历 查找
    201720181 JAVA实验站 第二周作业
    201720181 JAVA实验站 第三周作业
    201720181 团队名称 第一周 作业
    C#语言编写的基于directshow的音视频格式转换
  • 原文地址:https://www.cnblogs.com/yuan-jun/p/7806755.html
Copyright © 2011-2022 走看看