• SqlServer使用表变量或临时表遍历数据


    1、sql脚本使用表变量遍历数据示例:

    --表变量1
    declare @tempTb Table(ID int, Name nvarchar(64))
    
    --表变量2
    declare @DtTb Table(ID int, Name nvarchar(64))
    
    insert into @DtTb select top 100 ID,Name from [dbo].[Students]
    
    --声明循环的变量
    declare @ID int;
    
    --通过ID循环
    while exists(select ID from @DtTb)
    begin
        set rowcount 1; --对整个会话取数据有效,即若以下有查询语句,也是限定只取一条
        --select top 1 @ID = ID from @DtTb; --用 top 1 只对此句查询有效
        select @ID = ID from @DtTb;   
    
        --具体遍历业务
        insert into @tempTb select * from @DtTb where ID=@ID;
    
        set rowcount 0; --取消限定
        --遍历完一条一定要删掉此条,否则死循环!
        delete from @DtTb where ID=@ID;
    end
    
    select * from @tempTb;
    delete
    from @tempTb;

    2、sql脚本使用临时表遍历数据示例:

    --临时表1
    create Table #tempTb(ID int, Dbo nvarchar(64))
    
    --临时表2
    create Table #DtTb(ID int, Dbo nvarchar(64))
    
    insert into #DtTb select top 100 ID,Dbo from [AnyImageGuLou02].[grid].[BHosCheckES]
    
    --声明循环的变量
    declare @ID int;
    
    --通过ID循环
    while exists(select ID from #DtTb)
    begin
        --set rowcount 1; --对整个会话取数据有效,即若以下有查询语句,也是限定只取一条
        select top 1 @ID = ID from #DtTb; --用 top 1 只对此句查询有效
        --select @ID = ID from #DtTb;   
    
        --具体遍历业务
        insert into #tempTb select * from #DtTb where ID=@ID;
    
        --set rowcount 0; --取消限定
        --遍历完一条一定要删掉此条,否则死循环!
        delete from #DtTb where ID=@ID;
    end
    
    select * from #tempTb;
    --select * from #DtTb;
    
    --用完记得删掉临时表!
    drop table #tempTb;
    drop table #DtTb;
  • 相关阅读:
    数学人眼中的湖北(五)
    数学人眼中的湖北
    范德蒙德恒等式
    日本高中数学的学习范围
    怎样搞数学竞赛
    单色三角形问题
    shell wait 和sleep 对比
    上传本地文件到github仓库
    windows2008服务器设置系统启动时程序自动运行
    小程序运行报错:errMsg: "request:fail url not in domain list"
  • 原文地址:https://www.cnblogs.com/seanyan/p/13824732.html
Copyright © 2020-2023  润新知