一、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。
- /***************创建测试表*********************
- ****************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
/***************创建测试表********************* ****************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
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)
select PName,AddTime, PGuid from [Demo_Top] TableSample System(10 percent) --(77 row(s) affected)
注意这个百分比是表数据页的百分比,而不是记录数的百分比,因此记录数目是不确定的。