how to order 2 SQL Fields in asc and desc dynamically

后端 未结 4 1517
夕颜
夕颜 2021-01-18 22:46

I want to Order a SQL Select Query where there\'s 2 fields that are in the order by. I then need to decide if one is Descending and the other as Ascending. How is this done<

4条回答
  •  攒了一身酷
    2021-01-18 23:40

    You will have to create your SQL statement dynamically in order to use a variable:

    DECLARE @asc_desc VARCHAR(4);
    
    SET @asc_desc = 'DESC';
    
    DECLARE @sql NVARCHAR(1000);
    
    SET @sql = 'Select * from Customer Order By Date ' + @asc_desc + ', Name';
    
    EXEC sp_executesql @sql
    

    This will order Date DESCENDING and Name ASCENDING.

    You only need to add DESC if you want to use DESCENDING as ASCENDING is default.

提交回复
热议问题