使用 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
须大于当前正在处理在查询中的行的唯一标识符的新行。 例如:
/********** 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
/********** 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

浙公网安备 33010602011771号