SQL Server paging query

后端 未结 9 1369
攒了一身酷
攒了一身酷 2021-01-06 16:48

Urggggg! I\'ve been struggling with this for a long time! I can do it with MySQL so easy but not with SQL Server :(

Here are the simplified tables which should be jo

9条回答
  •  天命终不由人
    2021-01-06 17:37

    Try this with Sql Server 2008 + AdventureWorks database

    DECLARE @PageIndex INT, @RowsPerPage INT
    DECLARE @StartRow INT, @EndRow INT;
    
    SET @PageIndex = 1;
    SET @RowsPerPage = 500;
    SET @StartRow = ((@PageIndex - 1) * @RowsPerPage) + 1;
    SET @EndRow = @StartRow + @RowsPerPage - 1;
    
    --append#1
    WITH PAGE_ROWS
    AS
    (
    SELECT ROW_NUMBER() OVER(ORDER BY OrderDate DESC, SalesOrderNumber ASC) AS ROW_NO
        , COUNT(*) OVER() AS TOTAL_ROWS
        , *
    FROM( 
        --working query
        SELECT S.SalesOrderID
            , S.SalesOrderNumber
            , S.OrderDate
            , S.DueDate
            , S.ShipDate
            , S.Status
            , S.PurchaseOrderNumber
            , C.AccountNumber
            , P.FirstName, P.MiddleName, P.LastName
        FROM [Sales].[SalesOrderHeader] AS S
            LEFT OUTER JOIN [Sales].[Customer] AS C ON C.CustomerID=S.CustomerID
            LEFT OUTER JOIN [Person].[Person] AS P ON P.BusinessEntityID=C.PersonID
    --append#2
    ) AS Src)
    SELECT CEILING(TOTAL_ROWS/ CAST(@RowsPerPage AS DECIMAL(20,2))) AS TOTAL_PAGES
        ,*
    FROM PAGE_ROWS
    WHERE ROW_NO BETWEEN @StartRow AND @EndRow
    ORDER BY OrderDate DESC, SalesOrderNumber ASC
    

提交回复
热议问题