SQL如何从临时表优化插入到表

时间:2017-10-26 08:44:13

标签: sql database tsql optimization sql-execution-plan

我创建了一个程序,从各种项目(数据库)中动态收集一些记录到临时表中,并从我插入表中的临时表中。使用WHERE语句,但不幸的是,当我检查执行计划时,我发现,这个查询部分需要大量的负载。如何优化此INSERT部分或WHERE声明?

INSERT INTO dbo.PROJECTS_TESTS ( PROJECTID, ANOTHERTID, DOMAINID, is_test)
    SELECT * FROM #temp_Test AS tC
    WHERE NOT EXISTS (SELECT TOP 1 1 
                        FROM dbo.PROJECTS_TESTS AS ps WITH (NOLOCK)
                        WHERE ps.PROJECTID = tC.projectId 
                        AND ps.ANOTHERTID = tC.anotherLink 
                        AND ps.DOMAINID = tC.DOMAINID 
                        AND ps.is_test = tC.test_project 
                        )

1 个答案:

答案 0 :(得分:0)

我认为通过JOIN而不是EXISTS可以提供更好的服务。根据加入条件的基数(当前位于WHERE中),您可能还需要DISTINCT

INSERT INTO dbo.PROJECTS_TESTS ( PROJECTID, ANOTHERTID, DOMAINID, is_test)
    SELECT <maybe distinct> tC.* FROM #temp_Test AS tC
    LEFT OUTER JOIN  FROM dbo.PROJECTS_TESTS AS ps on
                        ps.PROJECTID = tC.projectId 
                        AND ps.ANOTHERTID = tC.anotherLink 
                        AND ps.DOMAINID = tC.DOMAINID 
                        AND ps.is_test = tC.test_project 

where ps.PROJECT ID IS NULL

或类似的东西