现在的位置: 首页 > 综合 > 正文

使用Transact-SQL 遍历结果集 (转)

2013年06月26日 ⁄ 综合 ⁄ 共 1538字 ⁄ 字号 评论关闭

使用 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

 

 

抱歉!评论已关闭.