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?