如何使用公用表表达式来过滤结果集

时间:2016-06-09 19:50:34

标签: sql-server-2008 tsql common-table-expression

我们正在尝试编写一个存储过程,允许在数据库服务器上执行排序分页。

我们正在将数据选择到公用表表达式(cte)中,该表达式包括该记录的行号。

在外部SELECT中,我们根据输入参数对结果进行排序,然后我们需要通过在WHERE子句中应用一种“skip / take”功能来应用分页。

如何在外部SELECT的WHERE子句中使用“RowNumberAfterOrderBy”用户?

CREATE PROCEDURE [dbo].[sp_API_GetData]
    @RequestedPage int,
    @PageSize int,
    @SortDirection nvarchar(30),
    @SortColumn nvarchar(30)
AS
BEGIN   
    DECLARE @TotalRecords int =  (SELECT COUNT(CaseId) FROM MyTable);

    SELECT @TotalRecords as 'TotalRecords'

    ;WITH cte AS
        (SELECT [CaseId]
            ,[ActivityId]
            ,ROW_NUMBER() OVER (ORDER BY sc.CaseId) AS RN
        FROM [dbo].[Cases] sc)
    SELECT [CaseId]
            ,[ActivityId]
            ,RN
            ,CASE @SortDirection 
                WHEN 'DESC' THEN ROW_NUMBER() OVER (ORDER BY RN DESC)
                WHEN 'ASC' THEN  ROW_NUMBER() OVER (ORDER BY RN)
             END AS RowNumberAfterOrderBy
    FROM cte
    --WHERE RowNumberAfterOrderBy BETWEEN (@PageSize * (@RequestedPage - 1) + 1) AND (@PageSize * @RequestedPage)
    ORDER BY 
        CASE WHEN @SortColumn = 'CaseID' AND @SortDirection = 'ASC' THEN CaseId END ASC,
        CASE WHEN @SortColumn = 'CaseID' AND @SortDirection = 'DESC' THEN CaseId END DESC,
        CASE WHEN @SortColumn = 'ActivityId' AND @SortDirection = 'ASC' THEN ActivityId END ASC,
        CASE WHEN @SortColumn = 'ActivityId' AND @SortDirection = 'DESC' THEN ActivityId END DESC   
END

-------------------

DECLARE @PageSize int = 10;
DECLARE @RequestedPage int = 1;
DECLARE @SortDirection nvarchar(5) = 'DESC';
DECLARE @SortColumn nvarchar(30) = 'CaseID';

EXEC [sp_API_GetCases] @RequestedPage, @PageSize, @SortDirection, @SortColumn

0 个答案:

没有答案