我有以下查询
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 @SortOrder = 1 THEN @SortColumn ELSE '' END ASC,
CASE WHEN @SortOrder = 2 THEN @SortColumn ELSE '' END DESC
END
所以如果我执行
DECLARE @return_value int
EXEC @return_value = [dbo].[usp_GetBills]
@PageNo = 2,
@PageSize = 10,
@SortOrder = N'1',
@SortColumn = 'BillNo'
SELECT 'Return Value' = @return_value
这个查询给我的结果总是w.r.t SortOrder。 SortOrder似乎无法正常工作。我提到this link
感谢。
答案 0 :(得分:0)
我们无法按顺序
传递动态列所以这个
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