程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> SqlServer數據庫 >> 關於SqlServer >> SQLServer 2008中SQL增強之二 Top新用途

SQLServer 2008中SQL增強之二 Top新用途

編輯:關於SqlServer
一、TOP替代Set RowCount
在SQL Server 2005之前的傳統SQL語句中,top語句是不支持局部變量的。見
http://www.jb51.net/article/27089.htm
此時可以使用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)
邀月注:本文版權由邀月和博客園共同所有,轉載請注明出處。
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved