I have this query to paginate the results and it was working fine on SQL Server 2012. However I had to move my database to SQL Server 2008 and now my stored procedure is not working. I did some research and got to know that OFFSET
does not work in SQL Server 2008. What alternative should I use now? How i achieve the same functionality with SQL Server 2008?
Here is my stored procedure:
CREATE PROCEDURE [dbo].[sp_JobSearch]
@EnteredKeyword nvarchar(200) = '',
@EnteredLocation nvarchar(200) = '',
@PageNumber INT = 1,
@PageSize INT = 40
AS
BEGIN
SELECT
MasterJob.Title, MasterJob.CompanyName,
MasterJob.ShortDesc, MasterJob.Url,MasterJob.PostedTime,
MasterJob.Location, JobBoard.JobBoardName
FROM
MasterJob
LEFT JOIN
JobBoard ON MasterJob.JobBoardId = JobBoard.JobBoardId
WHERE
(MasterJob.Title LIKE '%' + @EnteredKeyword + '%')
AND (MasterJob.Location LIKE '%' + @EnteredLocation + '%')
ORDER BY
[MasterJobId]
OFFSET @PageSize * (@PageNumber - 1) ROWS
FETCH NEXT @PageSize ROWS ONLY;
END
marc_s
9,0626 gold badges46 silver badges52 bronze badges
asked Apr 22, 2016 at 16:30
-
2sqlservercentral.com/articles/T-SQL/66030Aaron Bertrand– Aaron Bertrand2016年04月22日 16:38:21 +00:00Commented Apr 22, 2016 at 16:38
1 Answer 1
Use a Common Table Expression (CTE):
CREATE PROCEDURE [dbo].[sp_JobSearch]
@EnteredKeyword nvarchar(200) = '',
@EnteredLocation nvarchar(200) = '',
@PageNumber INT = 1,
@PageSize INT = 40
AS
BEGIN
WITH CTE AS
(
SELECT
ROW_NUMBER() OVER ( ORDER BY [MasterJobId] ) AS RowNum ,
MasterJob.Title, MasterJob.CompanyName, MasterJob.ShortDesc,
MasterJob.Url,MasterJob.PostedTime, MasterJob.Location, JobBoard.JobBoardName
FROM MasterJob
LEFT JOIN JobBoard ON MasterJob.JobBoardId = JobBoard.JobBoardId
WHERE
(MasterJob.Title LIKE '%' + @EnteredKeyword + '%')
AND( MasterJob.Location LIKE '%' + @EnteredLocation + '%' )
)
SELECT
Title, CompanyName, ShortDesc, Url, PostedTime, Location, JobBoardName
FROM CTE
WHERE
(RowNum > @PageSize * (@PageNumber - 1) )
AND
(RowNum <= @PageSize * @PageNumber )
Order By RowNum
END
ypercubeTM
99.7k13 gold badges217 silver badges306 bronze badges
answered Apr 22, 2016 at 17:57
-
Brilliant, Simply Brilliant!!! Exactly what I am looking for Thank you!Mark Kram– Mark Kram2017年09月12日 03:08:11 +00:00Commented Sep 12, 2017 at 3:08
lang-sql