T-SQL中替代游标遍历结果集的方法

1.借助主键字段实现方法

本方法先将数据复制到临时表,然后通过逐条读取并删除来实现替代游标遍历结果集:

set nocount on
select * into #tab1 from Account
declare @id int, @name nvarchar(20)
select top 1 @id=Id,@name=Usn from #tab1
delete from #tab1 where Id=@id
while @@rowcount>0
begin
    print @name
    select top 1 @id=Id,@name=Usn from #tab1
    delete from #tab1 where Id=@id
end
drop table #tab1

说明:本方法要求Id字段为主键且唯一,若数据量比较大,应使用create table创建临时表同时设置主键,否则处理时间会很长。

2.借助标识字段实现方法

若表中有标识字段,可借助min函数实现替代游标遍历结果集:

declare @id int, @name nvarchar(20)
select top 1 @id=min(Id) from Account
while @id is not null
begin
    select @name=Usn from Account where Id=@id
    print @name
    select top 1 @id=min(Id) from Account where Id>@id
end

若表中没有标识字段,可先将数据复制到临时表并创建标识字段,剩下的就和上边一样了:

set nocount on
select identity(int,1,1) as 'Id', Usn into #tab1 from Account
declare @id int, @name nvarchar(20)
select top 1 @id=min(Id) from #tab1
while @id is not null
begin
    select @name=Usn from #tab1 where Id=@id
    print @name
    select top 1 @id=min(Id) from #tab1 where Id>@id
end
drop table #tab1

本文方法在SQL Server2000/2005/2008测试通过。

评论: 0 | 引用: 0 | 查看次数: 3425
发表评论
登录后再发表评论!