Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ROW_NUMBER with Parameter

I am using SQL Server 2008. My procedure is

SELECT ContractorID ,
       Name,
       ROW_NUMBER() OVER (ORDER BY ContractorID) as RowNumber
FROM dbo.Contractor 

This is working but now I want to pass parameter into the OVER function.

I have tried :

DECLARE @OrderBy VARCHAR(MAX)
SET @OrderBy = 'ORDER BY ContractorID'

SELECT ContractorID ,
       Name,
       ROW_NUMBER() OVER (@OrderBy) as RowNumber
FROM dbo.Contractor 

this gives the error 'incorrect syntax near @OrderBy'? How can I do this? Thanks.

like image 834
Prashant16 Avatar asked Mar 23 '23 22:03

Prashant16


2 Answers

You may have a dynamic SQL and then execute it

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)
like image 147
Giannis Paraskevopoulos Avatar answered Apr 06 '23 05:04

Giannis Paraskevopoulos


Try this one -

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
like image 29
Devart Avatar answered Apr 06 '23 04:04

Devart