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

  • 相关阅读:
    C#面向对象之封装。
    python 数据处理学习pandas之DataFrame
    有用的vscode快捷键大全+自定义快捷键
    angular中控制器之间传递参数的方式
    angular.module 详解
    如何让类数组也使用数组的方法比如:forEach()
    CSS之flex兼容
    JavaScript中捕获/阻止捕获、冒泡/阻止冒泡
    Vue2.0 探索之路——生命周期和钩子函数的一些理解
    React 生命周期
  • 原文地址:https://www.cnblogs.com/LinWenQiang/p/15625100.html
Copyright © 2011-2022 走看看