我怎么能有一个动态变量设置行量返回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 (@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
在x0n的例子中,它应该是:
SET ROWCOUNT @top
SELECT * from sometable
SET ROWCOUNT 0
http://msdn.microsoft.com/en-us/library/ms188774.aspx
或者把变量放在括号里
DECLARE @top INT = 10;
SELECT TOP (@Top) *
FROM <table_name>;
SELECT TOP (@count) * FROM SomeTable
这只适用于SQL 2005+
也可以使用动态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)