Dynamic SELECT TOP @var In SQL Server
如何设置动态变量来设置SQL Server中要返回的行数? 以下是SQL Server 2005+中无效的语法:
1 2 3 4 | DECLARE @COUNT INT SET @COUNT = 20 SELECT TOP @COUNT * FROM SomeTable |
1 | SELECT TOP (@COUNT) * FROM SomeTable |
这仅适用于SQL 2005+
语法"select top(@var)..."仅适用于SQL SERVER 2005+。 对于SQL 2000,您可以执行以下操作:
1 2 3 4 5 | SET rowcount @top SELECT * FROM sometable SET rowcount 0 |
希望这可以帮助
[287]莪。
(编辑用rowcount替换@@ rowcount - 感谢augustlights)
在x0n的例子中,它应该是:
1 2 3 4 5 | SET ROWCOUNT @top SELECT * FROM sometable SET ROWCOUNT 0 |
http://msdn.microsoft.com/en-us/library/ms188774.aspx
1 2 3 4 5 | DECLARE @ROWS INT = 10 SELECT top (@ROWS) * FROM Employees ORDER BY 1 DESC -- optional to get the last records using the first column of the table |
或者您只需将变量放在括号中
1 2 3 4 | DECLARE @top INT = 10; SELECT TOP (@Top) * FROM <table_name>; |
它也可以使用动态SQL并使用exec命令执行它:
1 2 3 4 | DECLARE @SQL nvarchar(200), @COUNT INT SET @COUNT = 10 SET @SQL = N'select top ' + CAST(@COUNT AS nvarchar(4)) + ' * from table' EXEC (@SQL) |