SQLServer 2008中SQL增强之二 Top新用途
蚂蚁工房,报价网,4399城邦争霸无敌版
一、top替代set rowcount
在sql server 2005之前的传统sql语句中,top语句是不支持局部变量的。见
此时可以使用set rowcount,但是在sql server 2005/2008中,top通常执行得更快,所以应该用top关键字来取代set rowcount。
/***************创建测试表*********************
****************downmoo 3w@live.cn ***************/
if not object_id('[demo_top]') is null
drop table [demo_top]
go
create table [demo_top]
(pid int identity(1,1) primary key not null
,pname nvarchar(100) null
,addtime datetime null
,pguid nvarchar(40)
)
go
truncate table [demo_top]
/***************创建1002条测试数据*********************
****************downmoo 3w@live.cn ***************/
declare @d datetime
set @d=getdate()
declare @i int
set @i=1
while @i<=1002
begin
insert into [demo_top]
select cast(datepart(ms,getdate()) as nvarchar(3))+replicate('a',datepart(ss,getdate()))
,getdate()
,newid()
set @i=@i+1
end
--注意top关键字可以用于select,update和delete语句中
declare @percentage float
set @percentage=1
select top (@percentage) percent pname from [demo_top] order by pname
--注意是11行。(11 row(s) affected)
邀月注:如果只是需要一些样本,也可以使用tablesample,以下语句返回表demo_top的一定百分比的随机行
select pname,addtime, pguid from [demo_top]
tablesample system(10 percent)
--(77 row(s) affected)
注意这个百分比是表数据页的百分比,而不是记录数的百分比,因此记录数目是不确定的。
二、top分块修改数据
top的第二个关键改进是支持数据的分块操作。换句话说,避免在一个语句中执行非常大的操作,而把修改分成多个小块,这大大改善了大数据量、大访问量的表的并发性,可以用于大的报表或数据仓库应用程序。此外,分块操作可以避免日志的快速增长,因为前一操作完成后,可能会重用日志空间。如果操作中有事务,已经完成的修改数据已经可以用于查询,而不必等待所有的修改完成。
仍以上表为例:
while (select count(1) from [demo_top])>0
begin
delete top (202) from [demo_top]
end
/*
(202 row(s) affected)
(202 row(s) affected)
(202 row(s) affected)
(202 row(s) affected)
(194 row(s) affected)
*/
注意是每批删除202条数据,top也可以用于select和update语句,其中后者更为实用。
--select top(100)
--update top(100)
邀月注:本文版权由邀月和博客园共同所有,转载请注明出处。
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!!
点击进行留言回复
相关文章:
-
-
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...
[阅读全文]
-
-
-
-
-
网友评论