SQL: How do I use parameter for TOP like in SELECT TOP @amount? [duplicate]

柔情痞子 提交于 2019-12-20 10:59:32

问题


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"

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


回答1:


Need parenthesis, and only for SQL Server 2005 and above

SELECT TOP (@param1) ...



回答2:


For older versions of SQL Server, you can use:

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).



来源:https://stackoverflow.com/questions/1936496/sql-how-do-i-use-parameter-for-top-like-in-select-top-amount

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