表提示使用WITH

时间:2015-12-07 09:05:47

标签: sql sql-server sql-server-2008-r2

我有以下查询:

SELECT 
    *, 
    row_number() OVER (PARTITION BY CurveId, DeliveryDate, PeriodNumber 
                       ORDER BY publishdate ASC) AS [DuckCount]
FROM  
    mc.CURVEID_7017 
WHERE 
    CURVEID = 9152 
    AND DATEDIFF(hour,PublishDate, DeliveryDate) <= 24
OPTION (TABLE HINT(mc.CURVEID_7017, INDEX(IDX_CURVEID_7017)))

这很好用。现在我想使用WITH关键字,但无法让SQL Server允许表提示。它似乎在WITH (...)部分内无效。如果我将它移到外面,那么它无法报告我正在暗示的表不是查询的一部分。如果有人可以告诉我如何使用表提示执行下面的查询,我将非常感激!

WITH filteredNew AS 
(
    SELECT 
        *, 
        row_number() OVER (PARTITION BY CurveId, DeliveryDate, PeriodNumber 
                           ORDER BY publishdate ASC) AS [DuckCount]
    FROM  
        mc.CURVEID_7017 
    WHERE 
        CURVEID = 9152 
        AND DATEDIFF(hour,PublishDate, DeliveryDate) <= 24
    /*OPTION (TABLE HINT(mc.CURVEID_7017, INDEX(IDX_CURVEID_7017)))*/
)
SELECT
    DeliveryDate, value 
FROM 
    filteredNew
WHERE
    [DuckCount] = 1 
    AND DeliveryDate BETWEEN '1-sep-2015' AND '10-Nov-2015 23:59:59'
ORDER BY
    DeliveryDate ASC

HINT会产生很大的性能差异。任何帮助表示赞赏!

详细信息:SQL Server 2008 R2

如果我可以提供任何进一步的细节,请发表评论。

1 个答案:

答案 0 :(得分:1)

将提示移至末尾。见OPTION

  

只能使用语句指定一个OPTION子句。

语句是整个SELECT查询以及任何前面的CTE - 整个语句作为一个整体进行编译和优化。

WITH filteredNew AS (
SELECT *, row_number() 
OVER (PARTITION BY CurveId, DeliveryDate, PeriodNumber ORDER BY publishdate ASC) AS [DuckCount]
FROM  mc.CURVEID_7017 WHERE CURVEID = 9152 AND DATEDIFF(hour,PublishDate, DeliveryDate)<= 24)
select DeliveryDate, value from filteredNew
where [DuckCount] = 1 AND DeliveryDate BETWEEN '1-sep-2015' AND '10-Nov-2015 23:59:59'
order by DeliveryDate asc
OPTION (TABLE HINT(mc.CURVEID_7017, INDEX(IDX_CURVEID_7017)))