• SQLserver 中的循环遍历(普通循环和游标循环)


    1、普通循环执行SQL

    declare @i int       --声明
    set @i=1             --初始化
    while @i<=50         --执行条件
    begin 
    exec [dbo].[LineCalendar] @lineId= @i   --执行的SQL
    set @i=@i+1      --执行后变量加1
    end
    使用游标的顺序: 声名游标、打开游标、读取数据、关闭游标、删除游标。

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

    ---游标循环遍历--
    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
            --判断游标的状态
            --0 fetch语句成功    
            --1 fetch语句失败或此行不在结果集中    
            --2 被提取的行不存在
            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

    3、游标循环(事务)

    ---游标循环遍历--
    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

    原文:https://www.cnblogs.com/xielong/p/5941595.html

  • 相关阅读:
    [NOIP2018校模拟赛]T2矩阵分组 Matrix
    [NOIP2018校模拟赛]T1聚会 party
    python写一个邮箱伪造脚本
    python抢火车票的脚本
    git的使用
    python写一个翻译的小脚本
    python写的一个集合
    python调用metasploit里的MS-17-010模块进行漏洞攻击
    ssh爆破篇
    python查询完结篇
  • 原文地址:https://www.cnblogs.com/LinWenQiang/p/15625100.html
Copyright © 2020-2023  润新知