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

一个人想着一个人 提交于 2021-01-02 08:16:33

问题


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

回答1:


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.




回答2:


Simply omit the FETCH in the case where you want all rows:

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

IF (@take IS NULL)
BEGIN
    SELECT *
    FROM SomeTable
    ORDER BY SortOrder
    OFFSET @skip ROWS
END
ELSE
BEGIN
    SELECT *
    FROM SomeTable
    ORDER BY SortOrder
    OFFSET @skip ROWS
    FETCH NEXT @take ROWS ONLY
END


来源:https://stackoverflow.com/questions/34772015/using-offset-fetch-how-to-default-number-of-rows-to-all-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!