0

I am trying to do pagination in SQL SERVER and I am getting two errors on OFFSET and ROWS

CREATE PROCEDURE XYZ
@offset int,
@limit int, 
@order char(4),
@Id int
AS
BEGIN
SELECT * FROM TABLE
WHERE ID = @id
ORDER BY 
CASE WHEN @order = 'desc' THEN [TIME] END DESC,
CASE WHEN @order = 'asc' THEN [TIME] END ASC
*OFFSET* @offset FETCH ROWS NEXT @limit *ROWS* ONLY
END
GO

Error on OFFSET:

Incorrect Syntax near 'OFFSET'.

Error on ROWS (Second one):

Incorrect Syntax near 'ROWS'. Expecting FROM.

Can someone help me out with this ?

5
  • 1
    *OFFSET* @offset FETCH ROWS NEXT @limit *ROWS* ONLY should be OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY Commented Sep 5, 2017 at 8:41
  • 2
    Are you definitely targeting SQL Server 2012 or later? Commented Sep 5, 2017 at 8:44
  • @ZoharPeled I have used asterisk to identify the two keywords on which I am getting error. Commented Sep 5, 2017 at 8:44
  • @Damien_The_Unbeliever Okay, I think where the problem is. I am using SQL Server 2008. :| Commented Sep 5, 2017 at 8:47
  • @siddharth Yes, but my comment is referring to the fact that FETCH ROWS should be ROWS FETCH... Commented Sep 5, 2017 at 8:57

1 Answer 1

1

Well, in SQL Server 2008 you obviously can't use the fetch...next clause that was introduced in 2012.
However, this doesn't mean you can't do pagination.
One simple way is to use a cte with row_number:

;WITH CTE AS
(
    SELECT  *,  -- Don't be lazy, specify the Columns list...
            ROW_NUMBER() OVER
            (
                ORDER BY 
                CASE WHEN @order = 'desc' THEN [TIME] END DESC,
                CASE WHEN @order = 'asc' THEN [TIME] END ASC
            ) As rn 
    FROM TABLE
    WHERE ID = @id
)

SELECT * -- Don't be lazy, specify the Columns list...
FROM CTE
WHERE rn >= @offset
AND rn <= @offset + @limit
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.