带参数的ROW_NUMBER

时间:2013-08-02 06:45:48

标签: sql-server sql-server-2008

我正在使用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附近的语法不正确'?我怎样才能做到这一点?感谢。

3 个答案:

答案 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 

希望这会有所帮助..