標籤:
一、TOP替代Set RowCount
在SQL Server 2005之前的傳統SQL語句中,top語句是不支援局部變數的。見http://www.cnblogs.com/downmoon/archive/2007/12/29/1019686.html
此時可以使用Set RowCount,但是在SQL Server 2005/2008中,TOP通常執行得更快,所以應該用TOP關鍵字來取代Set RowCount。
/***************建立測試表********************* ****************downmoo [email protected] ***************/
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 [email protected] ***************/
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 Server 2008中SQL增強之二:Top新用途