2011-06-08 53 views
23

我正在创建一个SQL Server查询,它将采用一个参数并将其用作要返回的记录编号。SQL Server - 使用参数选择结果集的顶部X

在伪代码:

parameter returnCount 

select top returnCount * from table where x = y 

什么是正确的语法/代码来执行该操作?

+0

你正在使用哪个**版本的SQL Server? – 2011-06-08 21:18:55

+1

两岁的问题,你是否所以风暴士兵现在只是将它标记为重复?! – pithhelmet 2014-01-13 16:12:12

+0

永远不会太晚 – MatteoSp 2016-07-27 09:42:36

回答

51

在2005年的SqlServer和起来,做到这一点:

CREATE PROCEDURE GetResults (
    @ResultCount int 
) 
AS 

SELECT top(@ResultCount) FROM table where x = y 

对于更早的版本,使用:

CREATE PROCEDURE GetResults (
    @ResultCount int 
) 
AS 

SET ROWCOUNT @ResultCount 

SELECT * FROM table where x = y 

http://www.4guysfromrolla.com/webtech/070605-1.shtml了解更多信息。

15

与SQL Server 2005(而不是之前),你可以定义一个变量来确定您的TOP返回的行数:

DECLARE @returnCount INT 

SET @returnCount = 15 

SELECT TOP (@returnCount) * 
FROM dbo.table 
WHERE x = y