带有分页vb.net的Sql SELECT语句

问题描述 投票:0回答:4

我看过许多其他类似的问题,但无法让这个适用于我的陈述。 这是当前有效的 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 参数

sql vb.net select pagination
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"

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 

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

0
投票

您不能在 WHERE 子句中引用

ROW_NUMBER
,使用 通用表表达式 (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 开始,您将可以在 ORDER BY 中访问

OFFSET FETCH
,以帮助使分页更轻松、更高效。

© www.soinside.com 2019 - 2024. All rights reserved.