1

I have an existing stored procedure and I would like to apply the concept of paging by using OFFSET and FETCH NEXT.

However since this stored procedure already exists, and is called from other sources, I don't want to break it. I have added 2 optional parameters called @PageNumber INT = NULL and @NumberOfRecordsToRetrieve INT = NULL. I would like to know how to incorporate the logic into my query inside the stored procedure when these values are not supplied.

CREATE PROCEDURE TEST_PROCEDURE
    @Id INT,
    @PageNumber INT = NULL,
    @NumberOfRecordsToRetrieve INT = null
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @offsetRows INT, @nextRows INT, @maxCount INT

    IF(@PageNumber IS NOT NULL AND @NumberOfRecordsToRetrieve IS NOT NULL)
    BEGIN
        SET @offsetRows = (@PageNumber - 1) * @NumberOfRecordsToRetrieve;
        SET @nextRows = @NumberOfRecordsToRetrieve;
    END
    ELSE
    BEGIN
        SET @offsetRows = 0;
        SET @nextRows = 0;
    END

    SELECT 
        Id,
        Column2,
        Column3  
    FROM 
        ABCCustomers
    WHERE 
        Id = @Id

    UNION

    SELECT 
        Id,
        Column2,
        Column3  
    FROM 
        DEFCustomers
    WHERE 
        Id = @Id
    ORDER BY
        Column2
        -- this section needs to be applied only if the parameters have values
        OFFSET @offsetRows ROWS 
        FETCH NEXT @nextRows ROWS ONLY   
END

The offset and fetch next needs to be applied only when there is a value or else I will get an error. How do I solve this?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Fast Chip
  • 425
  • 1
  • 4
  • 16

2 Answers2

3

Simple, but perfectly acceptable:

IF @PageNumber IS NULL
  {Do query without OFFSET..FETCH}
ELSE
  {Do query with OFFSET..FETCH}
Tab Alleman
  • 31,483
  • 7
  • 36
  • 52
0

If you do not want to double your SQL statment: COALESCE is a alternative.

select id,
       name
  from user
 order by id
 offset COALESCE(@offset,0) rows
 fetch next COALESCE(@pageSize,2147483647) rows only

Like this answer:

Using OFFSET-FETCH, how to default number of rows to "all rows"?

MisterT
  • 138
  • 1
  • 10