簡體   English   中英

MS-SQLSERVER-使用ROW_NUMBER的SQL查詢花費很長時間,而查詢結果為0

[英]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 

我們有一個表MYTABLE,該表可能包含數百萬條記錄,當前它有1000萬條記錄。 上面的SQL查詢用於在我們的代碼中獲取分頁數據,在查詢給出結果之前它可以正常工作,但是如果查詢返回0個結果,則掛起數小時。 同樣,SQL Server在運行以上查詢時會開始消耗系統RAM,並且不會返回任何記錄。

另一方面,以下查詢可以很好地處理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

不管查詢中的問題如何,我都會介紹我通常實現分頁的方式:

作為輸入(例如,對於存儲過程):

@fromIndex int = 0 -- default starting from index 0
@count int = 10 -- default returning 10 items per page

通用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

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM