Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

L'ordinamento restituisce sempre lo stesso risultato

non possiamo passare le colonne dinamiche in ordine per clausola

Quindi questo

 Create procedure usp_GetBills
@PageNo         INT = 1,
@PageSize       INT = 10,
@SortOrder      INT = 1,
@SortColumn     VARCHAR(20) = ''
AS
BEGIN
DECLARE
@lSortColumn   VARCHAR(20),
@lFirstRec      INT,
@lLastRec       INT

SET @SortColumn = LTRIM(RTRIM(@SortColumn))
SET @lFirstRec  = (@PageNo - 1) *@PageSize
SET @lLastRec   = (@PageNo * @PageSize + 1)

;WITH CTE_Results 
AS(
SELECT ROW_NUMBER() OVER (ORDER BY(
@SortColumn))
AS ROWNUM,P.BillNo, P.PropertyNo, P.BillDate,  P.BillFromDate, P.BillToDate, P.BillAmount, P.DueDate, P.Status 
FROM Bill P)
SELECT * from CTE_Results
WHERE ROWNUM > @lFirstRec
AND ROWNUM   < @lLastRec
ORDER BY 
--ROWNUM * @SortOrder
CASE WHEN @SortIndex = 1 THEN BillNo END ASC,
CASE WHEN @SortIndex = 2 THEN BillNo END DESC, 
CASE WHEN @SortIndex = 1 THEN PropertyNo END ASC 
CASE WHEN @SortIndex = 2 THEN PropertyNo END DESC 

END