MS-SQLSERVER - 使用ROW_NUMBER的SQL查询需要很长时间,查询结果为0

时间:2011-11-08 07:06:47

标签: sql sql-server-2005

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

1 个答案:

答案 0 :(得分:0)

无论查询中出现什么问题,我都会提出我通常实现分页的方式:

作为输入(例如,对于存储过程):

@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

希望这有帮助。