我正在使用SQL Server 2008.我的程序是
SELECT ContractorID ,
Name,
ROW_NUMBER() OVER (ORDER BY ContractorID) as RowNumber
FROM dbo.Contractor
这是有效的,但现在我想将参数传递给OVER
函数。
我试过了:
DECLARE @OrderBy VARCHAR(MAX)
SET @OrderBy = 'ORDER BY ContractorID'
SELECT ContractorID ,
Name,
ROW_NUMBER() OVER (@OrderBy) as RowNumber
FROM dbo.Contractor
这会导致错误'@OrderBy附近的语法不正确'?我怎样才能做到这一点?感谢。
答案 0 :(得分:4)
您可能拥有动态SQL,然后执行它
DECLARE @OrderBy VARCHAR(MAX)
SET @OrderBy = 'ORDER BY ContractorID'
DECLARE @SQL VARCHAR(MAX)
SET @SQL =
'SELECT ContractorID ,
Name,
ROW_NUMBER() OVER (' + @OrderBy + ') as RowNumber
FROM dbo.Contractor '
EXEC (@SQL)
答案 1 :(得分:4)
试试这个 -
DECLARE @OrderBy VARCHAR(MAX)
SET @OrderBy = 'ORDER BY ContractorID'
DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL = 'SELECT ContractorID ,
Name,
ROW_NUMBER() OVER (' + @OrderBy + ') as RowNumber
FROM dbo.Contractor'
PRINT @SQL
EXEC sys.sp_executesql @SQL
答案 2 :(得分:-1)
为什么不尝试这个..
DECLARE @OrderBy VARCHAR(MAX)
SET @OrderBy = 'ContractorID'
SELECT ContractorID ,
Name,
ROW_NUMBER() OVER (order by @OrderBy) as RowNumber
FROM dbo.Contractor
希望这会有所帮助..