2010-12-23 106 views
1

我想創建一個存儲過程,它將整數值作爲@top,這樣我就可以在我的查詢中使用它,但它不允許我動態設置top的值。動態計算頂部數

select top @top * from (select url, 
count(1) as shared from tblshared 
group by url, uniqid having 
uniqid = @uniqid) as sha order by 
shared desc 

我想獲取頂級的n記錄表,所以我想傳遞的n在存儲過程中的價值,它將返回我,多家頂級記錄。

注意:我不想使用exec

謝謝。

+0

哪個版本的SQL Server? – 2010-12-23 11:34:27

+0

@使用sql server 2005 – 2010-12-23 11:43:50

回答

1

你可以使用SET ROWCOUNT

SET ROWCOUNT @top 
SELECT ... 
SET ROWCOUNT 0 
0
declare @v1 int 
set @v1 = 25 
set rowcount @v1 
select * from MyTable Order by DateColumn 
set rowcount 0 
+1

-1這適用於中間結果。所以聚合和子查詢可能是錯誤的。 TOP適用於預期 – gbn 2010-12-23 19:43:46

4

,如果在括號包裹@top將正常工作

select top (@top) * 
from ( 
    select url, count(1) as shared 
    from tblshared 
    group by url, uniqid 
    having [email protected]) as sha 
order by shared desc 
+0

得到此錯誤:消息170,級別15,狀態1,行1 行1:錯誤的語法附近'('。它顯示錯誤'(' – 2010-12-23 11:27:02

2

可以使用ROW_NUMBER() isntead的頂部

with t1 as(
    select url,row_number() over(
       partition by url, uniqid order by url, uniqid desc) as shared 
    from tblshared 
    where uniqid = @uniqid) 

select * from t1 where shared < @top 

REF