SQL Server 2008中SQL增強之二:Top新用途

來源:互聯網
上載者:User

標籤:

 

一、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新用途

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.