zoukankan      html  css  js  c++  java
  • 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;
  • 相关阅读:
    使用Google浏览器做真机页面调试
    JavaScript从作用域到闭包
    用canvas实现一个colorpicker
    你还在为移动端选择器picker插件而捉急吗?
    我是这样写文字轮播的
    高性能JS-DOM
    ExtJs4学习(四):Extjs 中id与itemId的差别
    MongoDB 安装与启动
    UML应用:业务内涵的分析抽象&表达
    MySQL 错误日志(Error Log)
  • 原文地址:https://www.cnblogs.com/seanyan/p/13824732.html
Copyright © 2011-2022 走看看