如何让我的FOR XML SQL查询更快?

时间:2014-02-01 01:18:43

标签: sql xml performance sqlxml

SELECT 
    *,
    ( -- Subquery to get associated rows in View2 as XML.
        SELECT
            *
        FROM View2
        WHERE
            View1_Print.SchedId = View2.SchedId AND
            PublishDay BETWEEN StartDate AND EndDate FOR XML PATH('Answer') 
    ) AS Answers
FROM View1_Print
FOR XML PATH('View1'), ROOT('ArrayOfView1');

上面的SQL似乎正确地检索了View1中的所有行以及View2中相关行的XML表示,这正是我想要的。问题是此查询需要四分钟才能执行。每个视图都有几千行。

当我使用join语句运行普通查询时,它只在六秒钟内执行,但我正在寻找一种将此结果序列化为XML的有效方法。这是我的查询,没有在六秒内运行的XML:

SELECT
*
FROM
View1 A
LEFT OUTER JOIN View2 B
    ON A.SchedId = B.SchedId AND B.PublishDay BETWEEN A.StartDate AND A.EndDate;

它应该检索完全相同的格式,那么为什么我的XML查询这么慢?

1 个答案:

答案 0 :(得分:1)

尝试使用外部apply而不是sub查询的查询,如下所示。请注意,这不是完整的答案,您需要根据您的要求进行修改并解决错误。

SELECT *,Answers.A,Answers.B 
FROM View1_Print
OUTER APPLY  ( -- Subquery to get associated rows in View2 as XML.
        SELECT
            View2.Col1 as A,View2.Col2 as B
        FROM View2
        WHERE
            View1_Print.SchedId = View2.SchedId AND
            PublishDay BETWEEN StartDate AND EndDate FOR XML PATH('Answer') 
    ) AS Answers
FOR XML PATH('View1'), ROOT('ArrayOfView1');