现在的位置: 首页 > 综合 > 正文

SQL Server 2008中SQL:Top新用途

2013年02月24日 ⁄ 综合 ⁄ 共 2678字 ⁄ 字号 评论关闭

一、TOP替代Set RowCount

在SQL Server 2005之前的传统SQL语句中,top语句是不支持局部变量的。见http://blog.csdn.net/downmoon/archive/2006/04/12/660557.aspx

此时可以使用Set RowCount,但是在SQL Server 2005/2008中,TOP通常执行得更快,所以应该用TOP关键字来取代Set RowCount。

  1. /***************创建测试表*********************
  2. ****************downmoo 3w@live.cn ***************/
  3. IF NOT OBJECT_ID('[Demo_Top]') IS NULL
  4. DROP TABLE [Demo_Top]
  5. GO
  6. Create table [Demo_Top]
  7. (PID int identity(1,1) primary key not null
  8. ,PName nvarchar(100) null
  9. ,AddTime dateTime null
  10. ,PGuid Nvarchar(40)
  11. )
  12. go
  13. truncate table [Demo_Top]
  14. /***************创建1002条测试数据*********************
  15. ****************downmoo 3w@live.cn ***************/
  16. declare @d datetime
  17. set @d=getdate()
  18. declare @i int
  19. set @i=1
  20. while
    @i<=1002
  21. begin
  22. insert into [Demo_Top]
  23. select cast(datepart(ms,getdate()) as nvarchar(3))+Replicate('A',datepart(ss,getdate()))
  24. ,getdate()
  25. ,NewID()
  26. set @i=@i+1
  27. end

--注意TOP关键字可以用于Select,Update和Delete语句中

  1. Declare @percentage float
  2. set @percentage=1
  3. select Top (@percentage) percent PName from [Demo_Top] order by PName


--注意是11行。(11 row(s) affected)

邀月注:如果只是需要一些样本,也可以使用TableSample,以下语句返回表Demo_Top的一定百分比的随机行

  1. select PName,AddTime, PGuid from [Demo_Top]
  2. TableSample System(10 percent)
  3. --(77 row(s) affected)

注意这个百分比是表数据页的百分比,而不是记录数的百分比,因此记录数目是不确定的。

二、TOP分块修改数据

TOP的第二个关键改进是支持数据的分块操作。换句话说,避免在一个语句中执行非常大的操作,而把修改分成多个小块,这大大改善了大数据量、大访问 量的表的并发性,可以用于大的报表或数据仓库应用程序。此外,分块操作可以避免日志的快速增长,因为前一操作完成后,可能会重用日志空间。如果操作中有事 务,已经完成的修改数据已经可以用于查询,而不必等待所有的修改完成。

仍以上表为例:

  1. while (select count(1) from [Demo_Top])>0
  2. begin
  3. delete top (202) from [Demo_Top]
  4. end
  5. /*
  6. (202 row(s) affected)
  7. (202 row(s) affected)
  8. (202 row(s) affected)
  9. (202 row(s) affected)
  10. (194 row(s) affected)
  11. */

注意是每批删除202条数据,TOP也可以用于Select和Update语句,其中后者更为实用。

--Select TOP(100)
--Update TOP(100)

邀月注:本文版权由邀月和CSDN共同所有,转载请注明出处。
助人等于自助! 3w@live.cn

抱歉!评论已关闭.