合并原因太慢,如何优化此查询

时间:2017-06-26 15:58:35

标签: sql sql-server

如何优化此查询。我正在使用merge来拉出插入的id

我看过执行计划。这导致排序成本增加。

还有其他方法可以做到这一点,而不是使用合并。我尝试过使用BY TARGET。还是很慢。我希望得到这个合并声明。

DECLARE @TEMP_STUDENT_DETAILS_ID AS TABLE (STUDENT_DETAILS_ID INT, SCHOOL_ID INT)

MERGE INTO DBO.STUDENT_DETAILS USING (
SELECT ISNULL(SUM(MARKS),0) AS MARKS, SCHOOL_ID
FROM DBO.OLD_STUDENT_DETAILS
WHERE SCHOOL_ID IS NOT NULL 
GROUP BY SCHOOL_ID) SRC ON 1 = 0 
WHEN NOT MATCHED BY TARGET THEN
INSERT (MARKS
       ,SCHOOL_ID
       ,CODE_ID
       ,CODE_VALUE
       ,CREATED_BY
       ,CREATED_DATE
       ,MODIFIED_BY
       ,MODIFIED_DATE)
VALUES (SRC.MARKS
       ,SRC.SCHOOL_ID
       ,101 --CODE_ID
       ,'ADA' --CODE_VALUE
       ,'Admin'
       ,GETDATE()
       ,'Admin'
       ,GETDATE())
OUTPUT INSERTED.STUDENT_DETAILS_ID, SRC.SCHOOL_ID INTO @TEMP_STUDENT_DETAILS_ID; 

1 个答案:

答案 0 :(得分:1)

您可以将OUTPUT语句与插入一起使用。 https://docs.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql这肯定比强制不匹配的合并更清晰。

INSERT DBO.STUDENT_DETAILS
(   MARKS
    ,SCHOOL_ID
    ,CODE_ID
    ,CODE_VALUE
    ,CREATED_BY
    ,CREATED_DATE
    ,MODIFIED_BY
    ,MODIFIED_DATE
)
OUTPUT INSERTED.STUDENT_DETAILS_ID, INSERTED.SCHOOL_ID INTO @TEMP_STUDENT_DETAILS_ID
SELECT ISNULL(SUM(MARKS),0) AS MARKS
    , SCHOOL_ID
    ,101 --CODE_ID
    ,'ADA' --CODE_VALUE
    ,'Admin'
    ,GETDATE()
    ,'Admin'
    ,GETDATE()
FROM DBO.OLD_STUDENT_DETAILS
WHERE SCHOOL_ID IS NOT NULL 
GROUP BY SCHOOL_ID