我创建了一个程序,从各种项目(数据库)中动态收集一些记录到临时表中,并从我插入表中的临时表中。使用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
)
答案 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
或类似的东西