SQL Server遍历表中记录的2种方法(使用表变量和游标)
iphone1发布会,沈思倩,盐城卫生职业技术学院教务处
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
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!!
点击进行留言回复
相关文章:
-
-
-
sql某个日期是当年的第几周
/* *周一作为一周的开始 *当年的1月1号所在的周算作第一周 */ CREATE function GetWeekIndexFirstDate ( @...
[阅读全文]
-
-
数据库SQL---范式
1、数据冗余导致的问题:冗余存储、更新异常、插入异常、删除异常。 2、函数依赖:一种完整性约束。 在关系模式r(R)中,α属于R,β属于R。 1)α函数...
[阅读全文]
-
-
数据库SQL---查询
1、查询所有列 select *from emp;--*表示所有的,from emp表示从emp表中查询。 2、查询指定列 select empno,e...
[阅读全文]
-
-
-
-
网友评论