Monday, June 25, 2018

ROW_NUMBER() OVER Dynamic @sortExpression

Step 1: Create Table

CREATE TABLE [dbo].[Student](
[ID] [int] NULL,
[Name] [varchar](50) NULL,
[City] [varchar](50) NULL
) ON [PRIMARY]
GO

Step 2: Insert Records in the table

insert into Student values (1,'Jack','california')
insert into Student values(2,'Lira','texas')
insert into Student values(3,'Aron','sweden')


ID Name City
1 Jack         california
3 Aron sweden
2 Lira         texas

Step 3: Execute Query

Declare @SortExp varchar(50) ='City'
Declare @strSql varchar(2000)

set @strSql='SELECT ROW_NUMBER() OVER ( ORDER BY '+@SortExp+' Asc) RowNumber,*
         FROM   Student  Order By RowNumber'
exec (@strSql)

Result:
RowNumber ID Name      City
1                  1 Jack             california
2                  3 Aron     sweden
3                  2 Lira              texas