select autoid from (SELECT ROW_NUMBER() OVER (ORDER
BY MYTABLE.DETECTEDUTC DESC) as rownum, autoId from
MYTABLE where MYTABLE.guid in (..guids..)) as tab1 where rownum >=1000 and rownum < 1020
We are having a table MYTABLE which may contain millions of records currently it is having 10 million records. above SQL query used to get paginated data in our code, it works fine till query giving results, but hangs for hours if query returning 0 results. Also SQL server start consuming system RAM while running above query and which is not returning any record.
on the other hand following query works fine with 0 results -
select autoid from (SELECT ROW_NUMBER() OVER (ORDER
BY MYTABLE.DETECTEDUTC DESC) as rownum, autoId from
MYTABLE where MYTABLE.guid in( ..guids..)) as tab1
Regardless of the issue in the query I am presenting the way I usually achieve paging:
As input (for a stored procedure for instance):
@fromIndex int = 0 -- default starting from index 0
@count int = 10 -- default returning 10 items per page
Generic SQL logic:
CREATE TABLE #PaginatedItems (
Column1 int, -- declare your needed columns here
Column2 varchar(50),
rowIndex int -- needed for pagination logic
);
WITH OrderedItems AS
(
SELECT
SourceTable.Col1, -- will end up in #PaginatedItems.Column1
SourceTable.Col2,
ROWNUMBER() OVER (
ORDER BY <sort criteria>
) AS rowIndex
FROM
SourceTable
)
INSERT INTO
#PaginatedItems
SELECT
*
FROM
OrderedItems
WHERE
rowIndex >= @fromIndex + 1 AND rowIndex <= @fromIndex + @count
SELECT * FROM #PaginatedItems -- the query that returns the items
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.