与交叉运行缓慢

时间:2015-11-17 19:29:46

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

尝试优化查询时,它会根据两个数据集上的INTERSECT更新表A中的记录。

UPDATE #TableA
SET IsFlag = CASE WHEN ISNULL(RJobFlag, 0) > 0 THEN 0 ELSE 1 END
FROM #TableA AS ABC
    OUTER APPLY (
                    SELECT 1 RJobFlag 
                    WHERE EXISTS (

                                    SELECT ABC.COLUMN1,ABC.COLUMN2,ABC.COLUMN3,ABC.COLUMN4,ABC.COLUMN5,ABC.COLUMN6,ABC.COLUMN7,ABC.COLUMN8,ABC.COLUMN8,ABC.COLUMN9,ABC.COLUMN10,StudentID,SubjectID
                                    INTERSECT
                                    SELECT XYZ.COLUMN1,XYZ.COLUMN2,XYZ.COLUMN3,XYZ.COLUMN4,XYZ.COLUMN5,XYZ.COLUMN6,XYZ.COLUMN7,XYZ.COLUMN8,XYZ.COLUMN8,XYZ.COLUMN9,XYZ.COLUMN10,StudentID,SubjectID
                                    FROM #TableB AS XYZ
                                    WHERE XYZ.COLUMN1 = (SELECT DISTINCT ID FROM #TableC MNOP WHERE MNOP.StudentID = ABC.StudentID)

                                    AND StudentID = ABC.StudentID
                                    AND SubjectID = ABC.SubjectID )

                    ) Subquery
WHERE ABC.COLUMN1= '2'

如果你有一些想法可以更好地优化它,那就很有用了。 感谢

1 个答案:

答案 0 :(得分:0)

这可能更糟糕,永远不会知道。

UPDATE  tA
SET     IsFlag = COALESCE(RJobFlag, 0)
FROM    #TableA tA
LEFT JOIN ( SELECT 1 RJobFlag, * 
                FROM #TableB tB 
                WHERE EXISTS (  SELECT * 
                                FROM #TableC tC 
                                WHERE tC.ID = tB.COLUMN1 AND tC.StudentID = tB.StudentID)
            ) tB 
                ON tA.StudentID = tB.StudentID
                AND tA.SubjectID = tB.SubjectID
                AND tA.COLUMN1 = tB.COLUMN1
                AND tA.COLUMN2 = tB.COLUMN2
                AND tA.COLUMN3 = tB.COLUMN3
                AND tA.COLUMN4 = tB.COLUMN4
                AND tA.COLUMN5 = tB.COLUMN5
                AND tA.COLUMN6 = tB.COLUMN6
                AND tA.COLUMN7 = tB.COLUMN7
                AND tA.COLUMN8 = tB.COLUMN8
                AND tA.COLUMN9 = tB.COLUMN9
                AND tA.COLUMN10 = tB.COLUMN10

如果#TableA有一堆记录,并且每次更新时都使用外部应用或外部连接,那么它将很慢,因为它必须更新每一条记录。也许有办法只更新已经改变的记录?