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