SQL Server遍历表中记录的2种方法(使用表变量和游标)

sql server遍历表一般都要用到游标,sql server中可以很容易的用游标实现循环,实现sql server遍历表中记录。本文将介绍利用使用表变量和游标实现数据库中表的遍历。

表变量来实现表的遍历

以下代码中,代码块之间的差异已经用灰色的背景标记。


复制代码 代码如下:

declare @temp table

(

[id] int identity(1, 1) ,

[name] varchar(10)

)

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’ )

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

但是这种方法,必须借助rowcount。但是使用 set rowcount 将可能会影响 delete、insert 和 update 语句。

所以修改上面while循环,改用top来选出首条记录。


复制代码 代码如下:

while exists ( select [id]

from @temp )

begin

select top 1

@tempid = [id] ,

@tempname = [name]

from @temp

delete from @temp

where [id] = @tempid

select *

from @temp

exec(‘drop table ‘+)

print ‘name:—-‘ + @tempname

end

这种方法也存在一个问题,需要将遍历过的行删除,事实上,我们在实际应用中可能并不想要遍历完一行就删除一行。

利用游标来遍历表

  游标是非常邪恶的一种存在,使用游标经常会比使用面向集合的方法慢2-3倍,当游标定义在大数据量时,这个比例还会增加。如果可能,尽量使用while,子查询,临时表,函数,表变量等来替代游标,记住,游标永远只是你最后无奈之下的选择,而不是首选。


复制代码 代码如下:

–定义表变量

declare @temp table

(

[id] int identity(1, 1) ,

[name] varchar(10)

)

declare @tempid int ,

@tempname varchar(10)

declare test_cursor cursor local for

select [id],[name] from @temp

–插入数据值

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’ )

–打开游标

open test_cursor

while @@fetch_status = 0

begin

fetch next from test_cursor into @tempid,@tempname

print ‘name:—-‘ + @tempname

end

close test_cursor

deallocate test_cursor

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐