我怎么能有一个动态变量设置行量返回SQL Server?以下语法在SQL Server 2005+中无效:
DECLARE @count int
SET @count = 20
SELECT TOP @count * FROM SomeTable
我怎么能有一个动态变量设置行量返回SQL Server?以下语法在SQL Server 2005+中无效:
DECLARE @count int
SET @count = 20
SELECT TOP @count * FROM SomeTable
语法“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
也可以使用动态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 @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