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

  • 相关阅读:
    CSP-S 代码基本框架
    Gradle build finished with 100 error(s) in 14s 629ms
    opencv2.3. 9+vs2012
    ButterKnife-- ButterKnife.bind(this); @BindView(R.id.bottomSelectView) BottomSelectView bottomSelectView;
    递归实现数组求和
    data structure begin!!
    递归实现全排列算法-161029
    简单粗暴-文件拓展名+任务管理器
    try to write a server
    在TextView中实时显示数据
  • 原文地址:https://www.cnblogs.com/dudu837/p/1781296.html
Copyright © 2011-2022 走看看