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

DECLARE @count int
SET @count = 20

SELECT TOP @count * FROM SomeTable

当前回答

SELECT TOP (@count) * FROM SomeTable

这只适用于SQL 2005+

其他回答

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

或者把变量放在括号里

DECLARE @top INT = 10;

SELECT TOP (@Top) *
FROM <table_name>;
SELECT TOP (@count) * FROM SomeTable

这只适用于SQL 2005+

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

set rowcount @top

select * from sometable

set rowcount 0 

希望这能有所帮助

爱信。

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

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

SET ROWCOUNT @top

SELECT * from sometable

SET ROWCOUNT 0

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