[英]MS-SQLSERVER - SQL Query using ROW_NUMBER taking long time with 0 result from query
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. 我们有一个表MYTABLE,该表可能包含数百万条记录,当前它有1000万条记录。 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.
上面的SQL查询用于在我们的代码中获取分页数据,在查询给出结果之前它可以正常工作,但是如果查询返回0个结果,则挂起数小时。 Also SQL server start consuming system RAM while running above query and which is not returning any record.
同样,SQL Server在运行以上查询时会开始消耗系统RAM,并且不会返回任何记录。
on the other hand following query works fine with 0 results - 另一方面,以下查询可以很好地处理0个结果-
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: 通用SQL逻辑:
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. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.