动态计算最高计数

时间:2010-12-23 11:10:10

标签: sql sql-server stored-procedures

我想创建一个存储过程,它将整数值作为@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

感谢。

4 个答案:

答案 0 :(得分:4)

如果将@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

答案 1 :(得分:2)

您可以使用ROW_NUMBER()代替顶部

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

答案 2 :(得分:1)

您可以使用SET ROWCOUNT

SET ROWCOUNT @top
SELECT ...
SET ROWCOUNT 0

答案 3 :(得分:0)

declare @v1 int
set @v1 = 25
set rowcount @v1
select * from MyTable Order by DateColumn
set rowcount 0