PDA

View Full Version : Làm sao để viết stored có select top N với N là biến?



nmd
10-09-2007, 19:31
Mình muốn viết 1 stored trong đó có select top N với N là para. Dạng giống như vậy
declare @topN int
set @topN=5
select top+ @topN+ * from tblArticles
order by CreatedDate desc;

Nhưng lại kô được. Xin vui lòng chỉ giúp mình với. Xin cám ơn nhiều.

xbacala
11-09-2007, 06:05
SQL 2000 không support TOP N là biến, SQL 2005 thì OK.

Nếu là SQL 2000 thì you dùng cách này:
declare @topN int
set @topN=5
SET ROWCOUNT @topN
select * from tblArticles
order by CreatedDate desc

SET ROWCOUNT 0 -- Reset rowcount limit

Cách trên cũng work với SQL 2005. Tuy nhiên, SQL 2005 support top N là biến, như sau:
declare @topN int
set @topN=5
select TOP (@topN) * from tblArticles
order by CreatedDate desc

nmd
11-09-2007, 11:45
Cám ơn bạn rất nhiều. Trình độ SQL kém quá. T_T

proitman
16-09-2007, 23:20
proc test
@count int
as
declare @strSQL varchar(1000)
begin
set @strSQL ='select top '+ @count +' * from Nhan_vien'
exec (@strSQL)
end