本文介绍您可以使用模拟一个类似于光标的 FETCH 的下一步逻辑存储的过程、 触发器或 TRANSACT-SQL 批处理中的各种方法。



用于进行交易的 SQL 语句迭代到结果集

有三种方法可用于循环访问一结果集使用 TRANSACT-SQL 语句。

一种方法是使用

temp

表。使用这种方法创建初始的 SELECT 语句的”快照”,并使用它作为一个基础”指针。例如:

/********** example 1 **********/ 

declare @au_id char( 11 )
if object_id('tempdb..#mytemp') is not null
drop   table   #mytemp

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
				

第二种方法是使用

最小

函数来一次”遍历”表的一行。此方法将捕获新行添加的存储的过程开始执行后,新的行都有一个大于当前正在处理查询中的行的唯一标识符。例如:

/********** 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