how to order 2 SQL Fields in asc and desc dynamically

后端 未结 4 1651
夕颜
夕颜 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:23

    Here is the solution
    
    Explanation:
    1. Ordering the row number on the basis of SQL input param  order by (DESC, ASC)
    2. Againt ordering the row number in outer query
    
    Try this code (working)
    
    DECLARE @PageNum int
    DECLARE @PageSize int
    DECLARE @TotalRowsNum int
    DECLARE @SortColumn varchar(200)
    DECLARE @SortOrder varchar(5)
    
    SET @PageNum = 4;
    SET @PageSize = 10;
    SET @SortColumn = 'CODE_ID';
    SET @SortOrder = 'DESC';
    
    WITH QueryResult AS
    (
    
    SELECT *,
    CASE @SortOrder WHEN 'ASC' THEN
    ROW_NUMBER() OVER(ORDER BY @SortColumn ASC) 
    ELSE
    ROW_NUMBER() OVER(ORDER BY @SortColumn DESC) 
    END AS 'RowNumber'
    
    FROM TABLE_NAME 
    ) 
    SELECT * FROM QueryResult
    WHERE RowNumber BETWEEN (@PageNum - 1) * @PageSize + 1 AND @PageNum * @PageSize
    ORDER BY RowNumber ASC 
    

提交回复
热议问题