Click here to Skip to main content
15,893,923 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I have to perform order by based on condition. For this I have written the below code

For this First i have declared one variable after i am trying to use that variable.But it is not working .
SQL
DECLARE @order Nvarchar(50)
--set @order='DATEDIFF(day,EffectiveDate,getdate())';

set @order='Accountname DESC';

WITH Result as (
        SELECT ROW_NUMBER()
        OVER (ORDER BY @order) AS Row,
        Number,
        Accountname,
        LOB,
        History.Policystatus As [Status],
        Cast(Quote.EffectiveDate as date) As ExpirationDate ,
        DATEDIFF(day,EffectiveDate,getdate()) as NoOfDays
        FROM MyTable WITH (NOLOCK)
        WHERE Userid='1'  )
 select * from Result where Row Between 1 AND 10


Please help on this.

Thanks,
Nagasubba Reddy
Posted
Comments
Kornfeld Eliyahu Peter 11-Aug-15 9:26am    
What do you mean by 'not working'?

Hi Nagasubba,

You can use dynamic SQL .
Example :-

For Example i have taken only 3,4 column..

SQL
Create Table #MyTable (Number varchar(max),Accountname varchar(max) ,LOB varchar(max) )
INSert into #MyTable
Values ( 'one','vijay dinanath','Developemnt'), 
 ( 'Two','Mangal','Developemnt'), 
 ( 'Three','Amrendra','Developemnt')

DECLARE @order Nvarchar(50)
--set @order='DATEDIFF(day,EffectiveDate,getdate())';

set @order='Accountname asc';


 Set @Query='
;WITH Result as (
        SELECT ROW_NUMBER()
        OVER (ORDER BY '+@order+') AS Row,
        Number,
        Accountname,
        LOB
        FROM #MyTable WITH (NOLOCK)
         )
 select * from Result where Row Between 1 AND 10'
 Exec (@Query);
 
Share this answer
 
v2
You need to use dynamic SQL to to be able to specify the ORDER BY clause dynamically.

SQL
DECLARE @order Nvarchar(50) = 'Accountname DESC';

DECLARE @newLine AS CHAR(2) = CHAR(13) + CHAR(10)

DECLARE @sql NVARCHAR(MAX) = N'SELECT' + @newLine +
        '    Number,' + @newLine +
        '    Accountname,' + @newLine +
        '    LOB,' + @newLine +
        '    History.Policystatus As [Status],' + @newLine +
        '    Cast(Quote.EffectiveDate as date) As ExpirationDate ,' + @newLine +
        '    DATEDIFF(day,EffectiveDate,getdate()) as NoOfDays' + @newLine +
        'FROM MyTable WITH (NOLOCK)' + @newLine +
        'WHERE Userid=''1''' + @newLine +
        'ORDER BY ' + @order;

--PRINT @sql;
EXEC sp_execute @sql;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900