且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在order by子句中使用变量

更新时间:2023-10-06 11:37:04

嗨Nagasubba,



您可以使用动态SQL。

示例: -



例如我只拍了3,4列..



Hi Nagasubba,

You can use dynamic SQL .
Example :-

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

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);


您需要使用动态SQL来指定 ORDER BY $ c动态$ c>子句。



You need to use dynamic SQL to to be able to specify the ORDER BY clause dynamically.

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;