您的位置:首页 > 数据库

Transact-SQL语句遍历结果集的三种方法

2016-03-22 17:23 369 查看
Transact-SQL语句是可以实现遍历的,有三种方法使用可以通过使用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_idau_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_idau_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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: