dynamicselect顶部@var在SQL Server中

我怎样才能有一个dynamicvariables设置SQL Server中返回的行数量? 以下是SQL Server 2005+中的无效语法:

DECLARE @count int SET @count = 20 SELECT TOP @count * FROM SomeTable 
 SELECT TOP (@count) * FROM SomeTable 

这只适用于SQL 2005+

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

 set rowcount @top select * from sometable set rowcount 0 

希望这可以帮助

[287]莪。

(编辑用rowcountreplace@@ rowcount – 谢谢augustlights)

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

 SET ROWCOUNT @top SELECT * from sometable SET ROWCOUNT 0 

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

还可以使用dynamicSQL并使用exec命令执行它:

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

或者你只是把variables放在括号中

 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 fist column of the table