Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Envision a stored procedure which takes @skip (offset) and @take (maximum number of rows to return. If @take is null, then I want to return "all rows after applying the offset".

I can accomplish this by counting the number of rows in the table/view if @take is null, but then I have to perform two queries which is, of course, not optimal. I was hoping there was an option similar to FETCH [NEXT] ALL ROWS.

DECLARE @skip BIGINT = 0;
DECLARE @take BIGINT = NULL;

IF (@take IS NULL) SET @take = (SELECT COUNT(*) FROM SomeTable);

SELECT *
FROM SomeTable
ORDER BY SortOrder
OFFSET @skip ROWS
FETCH NEXT @take ROWS ONLY
like image 688
Josh M. Avatar asked Jan 13 '16 16:01

Josh M.


1 Answers

You could use COALESCE:

DECLARE @skip BIGINT = 0;
DECLARE @take BIGINT = NULL;

SELECT *
FROM SomeTable
ORDER BY SortOrder
OFFSET COALESCE(@skip,0) ROWS
FETCH NEXT COALESCE(@take,0x7ffffff) ROWS ONLY

LiveDemo

0x7ffffff is the same as 2147483647 max INT value.

When @skip and @take are not provided it will get first 2^31-1 records from table.

like image 109
Lukasz Szozda Avatar answered Sep 22 '22 11:09

Lukasz Szozda