在SQL Server中动态选择TOP @var

我怎么能有一个动态变量设置行量返回SQL Server?以下语法在SQL Server 2005+中无效:

DECLARE @count int
SET @count = 20


SELECT TOP @count * FROM SomeTable
161440 次浏览
SELECT TOP (@count) * FROM SomeTable

这只适用于SQL 2005+

语法“select top (@var)…”只适用于SQL SERVER 2005+。对于SQL 2000,你可以这样做:

set rowcount @top


select * from sometable


set rowcount 0

希望这能有所帮助

Oisin。

(编辑后用rowcount替换@@rowcount -谢谢augustlights)

在x0n的例子中,它应该是:

SET ROWCOUNT @top


SELECT * from sometable


SET ROWCOUNT 0

http://msdn.microsoft.com/en-us/library/ms188774.aspx

也可以使用动态SQL并使用exec命令执行:

declare @sql  nvarchar(200), @count int
set @count = 10
set @sql = N'select top ' + cast(@count as nvarchar(4)) + ' * from table'
exec (@sql)

或者把变量放在括号里

DECLARE @top INT = 10;


SELECT TOP (@Top) *
FROM <table_name>;
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