SQL Server - 使用参数选择结果集的前X [重复]

时间:2022-12-09 23:33:56

This question already has an answer here:

这个问题在这里已有答案:

I am creating a SQL Server query that will take a parameter and use that as the record number to return.

我正在创建一个SQL Server查询,它将获取一个参数并将其用作要返回的记录号。

In pseudo code:

在伪代码中:

parameter returnCount

select top returnCount * from table where x = y

What is the correct syntax/code to perform that operation?

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

2 个解决方案

#1


51  

In SqlServer 2005 and up, do this:

在SqlServer 2005及更高版本中,执行以下操作:

CREATE PROCEDURE GetResults    (
    @ResultCount   int
)
AS

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

For earlier versions, use:

对于早期版本,请使用:

CREATE PROCEDURE GetResults    (
    @ResultCount   int
)
AS

SET ROWCOUNT @ResultCount

SELECT * FROM table where x = y

http://www.4guysfromrolla.com/webtech/070605-1.shtml for more information.

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

#2


16  

As of SQL Server 2005 (but not before that), you can define a variable to determine your number of TOP rows returned:

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

DECLARE @returnCount INT

SET @returnCount = 15

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

#1


51  

In SqlServer 2005 and up, do this:

在SqlServer 2005及更高版本中,执行以下操作:

CREATE PROCEDURE GetResults    (
    @ResultCount   int
)
AS

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

For earlier versions, use:

对于早期版本,请使用:

CREATE PROCEDURE GetResults    (
    @ResultCount   int
)
AS

SET ROWCOUNT @ResultCount

SELECT * FROM table where x = y

http://www.4guysfromrolla.com/webtech/070605-1.shtml for more information.

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

#2


16  

As of SQL Server 2005 (but not before that), you can define a variable to determine your number of TOP rows returned:

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

DECLARE @returnCount INT

SET @returnCount = 15

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