SQL:如何在SELECT TOP @amount中使用TOP参数? [重复]

时间:2022-06-18 09:25:26

This question already has an answer here:

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

Using the vs2008 query builder, I’m trying to make a query that gets a parameter for the "TOP" Command, and then I face an error "Error in top expression"

使用vs2008查询构建器,我正在尝试进行查询以获取“TOP”命令的参数,然后我遇到错误“*表达式中的错误”

Works:

作品:

SELECT TOP 5 * FROM dbo.SomeTable
WHERE SomeColumn = SomeValue

Doesn't Work:

不起作用:

SELECT TOP @param1 * FROM dbo.SomeTable
WHERE SomeColumn = SomeValue

alt text http://www.freeimagehosting.net/uploads/f9b9354577.jpg

alt text http://www.freeimagehosting.net/uploads/f9b9354577.jpg

2 个解决方案

#1


69  

Need parenthesis, and only for SQL Server 2005 and above

需要括号,仅适用于SQL Server 2005及更高版本

SELECT TOP (@param1) ...

#2


6  

For older versions of SQL Server, you can use:

对于旧版本的SQL Server,您可以使用:

SET ROWCOUNT @NumberOfResults
SELECT * FROM MyTable
SET ROWCOUNT 0

However, you should not use this technique on 2008:

但是,您不应该在2008年使用此技术:

Using SET ROWCOUNT will not affect DELETE, INSERT, and UPDATE statements in the next release of SQL Server (2008). Do not use SET ROWCOUNT with DELETE, INSERT, and UPDATE statements in new development work, and plan to modify applications that currently use it. Also, for DELETE, INSERT, and UPDATE statements that currently use SET ROWCOUNT, we recommend that you rewrite them to use the TOP syntax. For more information, see DELETE (Transact-SQL), INSERT (Transact-SQL), or UPDATE (Transact-SQL).

在下一版本的SQL Server(2008)中,使用SET ROWCOUNT不会影响DELETE,INSERT和UPDATE语句。不要在新的开发工作中将SET ROWCOUNT与DELETE,INSERT和UPDATE语句一起使用,并计划修改当前使用它的应用程序。此外,对于当前使用SET ROWCOUNT的DELETE,INSERT和UPDATE语句,我们建议您重写它们以使用TOP语法。有关更多信息,请参阅DELETE(Transact-SQL),INSERT(Transact-SQL)或UPDATE(Transact-SQL)。

#1


69  

Need parenthesis, and only for SQL Server 2005 and above

需要括号,仅适用于SQL Server 2005及更高版本

SELECT TOP (@param1) ...

#2


6  

For older versions of SQL Server, you can use:

对于旧版本的SQL Server,您可以使用:

SET ROWCOUNT @NumberOfResults
SELECT * FROM MyTable
SET ROWCOUNT 0

However, you should not use this technique on 2008:

但是,您不应该在2008年使用此技术:

Using SET ROWCOUNT will not affect DELETE, INSERT, and UPDATE statements in the next release of SQL Server (2008). Do not use SET ROWCOUNT with DELETE, INSERT, and UPDATE statements in new development work, and plan to modify applications that currently use it. Also, for DELETE, INSERT, and UPDATE statements that currently use SET ROWCOUNT, we recommend that you rewrite them to use the TOP syntax. For more information, see DELETE (Transact-SQL), INSERT (Transact-SQL), or UPDATE (Transact-SQL).

在下一版本的SQL Server(2008)中,使用SET ROWCOUNT不会影响DELETE,INSERT和UPDATE语句。不要在新的开发工作中将SET ROWCOUNT与DELETE,INSERT和UPDATE语句一起使用,并计划修改当前使用它的应用程序。此外,对于当前使用SET ROWCOUNT的DELETE,INSERT和UPDATE语句,我们建议您重写它们以使用TOP语法。有关更多信息,请参阅DELETE(Transact-SQL),INSERT(Transact-SQL)或UPDATE(Transact-SQL)。