0

我查看了许多其他类似的问题,但无法让这适用于我的陈述。这是当前有效的 SELECT 语句,我需要添加分页。

      "SELECT TOP 15 * FROM  tblEvents WHERE (dbo.fnEventSearchDistance(@CityLat, " & _
      "@CityLong, latitude, longitude) <= @Radius AND (StartDate >= GETDATE())) "

这是我能得到的最接近的。

      "SELECT ROW_NUMBER() OVER(ORDER BY StartDate) AS RowNum, * FROM tblEvents " & _
      "WHERE RowNum BETWEEN ((@PageNum - 1) * @PageSize + 1) " & _
      "AND (@PageNum * @PageSize) " & _
      "ORDER BY StartDate"

      comm2.Parameters.AddWithValue("@PageSize", 25)
      comm2.Parameters.AddWithValue("@PageNum", 2)

我需要一个 SELECT 语句来重写第一个 SELECT 语句以合并分页,我可以在其中添加 pageSize 和 pageNum 参数

4

4 回答 4

2

假设 SQL Server 2008 和更早版本,你应该试试这个:

"SELECT col1, col2 FROM (SELECT ROW_NUMBER() OVER(ORDER BY StartDate) AS RowNum, * FROM tblEvents) AS E " & _
"WHERE RowNum BETWEEN ((@PageNum - 1) * @PageSize + 1) " & _
"AND (@PageNum * @PageSize) " & _
"ORDER BY StartDate"

请注意,我放col1, col2了选择,你应该把你需要的列放在那里。对于 SQL Server 2012,这非常简单:

"SELECT * FROM tblEvents ORDER BY StartDate " & _ 
"OFFSET (@PageNum - 1) * @PageSize ROWS FETCH NEXT @PageNum ROWS ONLY"
于 2012-07-12T15:26:26.357 回答
1
CREATE  PROCEDURE [dbo].[usp_PageResults_NAI] 
(
    @startRowIndex int,
    @maximumRows int
)
AS

DECLARE @first_id int, @startRow int

-- A check can be added to make sure @startRowIndex isn't > count(1)
-- from employees before doing any actual work unless it is guaranteed
-- the caller won't do that

-- Get the first employeeID for our page of records
SET ROWCOUNT @startRowIndex
SELECT @first_id = employeeID FROM employees ORDER BY employeeid

-- Now, set the row count to MaximumRows and get
-- all records >= @first_id
SET ROWCOUNT @maximumRows

SELECT e.*, d.name as DepartmentName 
FROM employees e
   INNER JOIN Departments D ON
       e.DepartmentID = d.DepartmentID
WHERE employeeid >= @first_id
ORDER BY e.EmployeeID

SET ROWCOUNT 0

GO 
于 2012-07-12T15:29:15.577 回答
0

试试这个:

;With ranked AS
(
   SELECT ROW_NUMBER() OVER(ORDER BY StartDate) AS RowNum,  * 
   FROM tblEvents
)
SELECT * FROM Ranked
WHERE RowNum BETWEEN ((@PageNum - 1) * @PageSize + 1)
    AND (@PageNum * @PageSize)
    ORDER BY StartDate
于 2012-07-12T15:25:24.053 回答
0

您不能在子句中引用ROW_NUMBERWHERE,使用公用表表达式 (CTE)可以帮助进行分页。

WITH Paging AS
(
   SELECT ROW_NUMBER() OVER (ORDER BY StartDate) AS RowNum
    , *
   FROM tblEvents
)
SELECT *
FROM Paging AS p
WHERE p.RowNum BETWEEN ((@PageNum - 1) * @PageSize + 1)
   AND (@PageNum * @PageSize)
ORDER BY p.StartDate ASC;

从 SQL 2012 开始,您将可以访问OFFSET FETCHORDER BY帮助更轻松、更高效地进行分页。

于 2012-07-12T15:31:11.063 回答