how to get top n rows from a table where value of n is passed at run-time?

痞子三分冷 提交于 2020-01-13 11:07:41

问题


How to get top n rows from a table where value of n is passed at run-time?


回答1:


In SQL Server 2005 and beyond you can actually parameterise the top command.

The code below is from MSDN

USE AdventureWorks;
GO
DECLARE @p AS int;
SELECT @p=10
SELECT TOP(@p)*
FROM HumanResources.Employee;
GO

In earlier versions of SQL Server you will need to either use rowcount or dynamic sql.




回答2:


You can use set rowcount. To get the first 100, for example:

declare @myrowcount = 100

set rowcount @myrowcount      
select ..... from ... where...order by

since you can use either of:

SET ROWCOUNT { number | @number_var }



来源:https://stackoverflow.com/questions/2260767/how-to-get-top-n-rows-from-a-table-where-value-of-n-is-passed-at-run-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!