SQL:如何在 SELECT TOP @amount 中使用 TOP 参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1936496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQL: How do I use parameter for TOP like in SELECT TOP @amount?
提问by Alon Amir
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
回答by gbn
Need parenthesis, and only for SQL Server 2005 and above
需要括号,且仅适用于 SQL Server 2005 及以上
SELECT TOP (@param1) ...
回答by Mike Valenty
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:
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).
使用 SET ROWCOUNT 不会影响下一版本的 SQL Server (2008) 中的 DELETE、INSERT 和 UPDATE 语句。不要在新的开发工作中将 SET ROWCOUNT 与 DELETE、INSERT 和 UPDATE 语句一起使用,并计划修改当前使用它的应用程序。此外,对于当前使用 SET ROWCOUNT 的 DELETE、INSERT 和 UPDATE 语句,我们建议您重写它们以使用 TOP 语法。有关详细信息,请参阅 DELETE (Transact-SQL)、INSERT (Transact-SQL) 或 UPDATE (Transact-SQL)。