木子屋 Dnawo's BLOG

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

👤 dnawo 📅 2013-04-25 👁 4353 👍 0 💬 0 🔄 本站原创
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)

暂无评论。

计算题
评论需审核通过后显示
← 上一篇 HttpWebRequest使用HEAD方法获取远程文件大小 下一篇 → qq可以上网页打不开解决方法