• 使用TransactSQL 遍历结果集 (转)


    使用 Transact-SQL 语句循环结果集

    有三种方法使用可以通过使用 Transact-SQL 语句遍历一个结果集。

    一种方法是使用 temp 表。 使用这种方法您创建的初始的 SELECT 语句的"快照"并将其用作基础"指针"。 例如:  
    /**//********** example 1 **********/

    declare @au_id char( 11 )

    set rowcount 0
    select * into #mytemp from authors

    set rowcount 1

    select @au_id = au_id from #mytemp

    while @@rowcount <> 0
    begin
        
    set rowcount 0
        
    select * from #mytemp where au_id = @au_id
        
    delete #mytemp where au_id = @au_id

        
    set rowcount 1
        
    select @au_id = au_id from #mytemp<BR/>
    end
    set rowcount 0
            
    第二个的方法是表格的一行"遍历"每次使用 Min 函数。 此方法捕获添加存储的过程开始执行之后, 假设新行必
    须大于当前正在处理在查询中的行的唯一标识符的新行。 例如:

    /**//********** example 2 **********/

    declare @au_id char( 11 )

    select @au_id = min( au_id ) from authors

    while @au_id is not null
    begin
        
    select * from authors where au_id = @au_id
        
    select @au_id = min( au_id ) from authors where au_id > @au_id
    end
    注意 : 两个示例 1 和 2,则假定源表中的每个行唯一的标识符存在。 在某些情况下,可能存在没有唯一标识符。 如果是这种情况,您可以修改 temp 表方法使用新创建的键列。 例如:
    /**//********** example 3 **********/

    set rowcount 0
    select NULL mykey, * into #mytemp from authors

    set rowcount 1
    update #mytemp set mykey = 1

    while @@rowcount > 0
    begin
        
    set rowcount 0
        
    select * from #mytemp where mykey = 1
        
    delete #mytemp where mykey = 1
        
    set rowcount 1
        
    update #mytemp set mykey = 1
    end
    set rowcount 0

    ---------------


    declare @temp table
    (
        [id] int IDENTITY(1,1),
        [Name] varchar(10)
    )
    --select * from @temp
    declare @tempId int,@tempName varchar(10)

    insert into @temp values('a')
    insert into @temp values('b')
    insert into @temp values('c')
    insert into @temp values('d')
    insert into @temp values('e')


    --select * from @temp


    WHILE EXISTS(select [id] from @temp)
    begin
    SET ROWCOUNT 1
    select @tempId = [id],@tempName=[Name] from @temp
    SET ROWCOUNT 0
    delete from @temp where [id] = @tempId

    print 'Name:----'+@tempName
    end

     
  • 相关阅读:
    ASP.NET 防盗链的实现[HttpHandler]
    html打印表格每页都有的表头和打印分页
    spring是怎样管理mybatis的及注入mybatis mapper bean的
    浅谈Log4j和Log4j2的区别
    git tag — 标签相关操作
    java cocurrent包
    线程实现异步
    使用Shell脚本查找程序对应的进程ID,并杀死进程
    shell脚本监测文件变化
    spring boot的几种配置类型
  • 原文地址:https://www.cnblogs.com/rainbowzc/p/1804887.html
Copyright © 2020-2023  润新知