I have looked at many other similar questions and cant get this to work for my statement. This is the SELECT statement that currently works, and I need to add paging.
"SELECT TOP 15 * FROM tblEvents WHERE (dbo.fnEventSearchDistance(@CityLat, " & _
"@CityLong, latitude, longitude) <= @Radius AND (StartDate >= GETDATE())) "
This is the closest I have been able to get.
"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)
I need a SELECT Statement that rewrites the first SELECT statement to incorporate paging, where I can add pageSize and pageNum parameters
Assuming SQL Server 2008 and previous, you should try this:
"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"
Note that I put col1, col2
on the select, you should put the columns you need there. For SQL Server 2012, this is quite simpler:
"SELECT * FROM tblEvents ORDER BY StartDate " & _
"OFFSET (@PageNum - 1) * @PageSize ROWS FETCH NEXT @PageNum ROWS ONLY"
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
Try this instead:
;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
You cannot reference ROW_NUMBER in the WHERE
clause, using a Common Table Expression (CTE) can help with paging.
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;
Starting in SQL 2012, you will have access to OFFSET FETCH in your ORDER BY
to help making paging easier, and more efficient.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.