SQL 如何优化从临时 table 插入到 table
SQL How to optimize insert to table from temporary table
我创建了从各种项目(数据库)动态收集一些记录到临时 table 中的过程,然后从那个临时 table 我插入到 table 中。使用 WHERE
statement ,但不幸的是,当我检查执行计划时,我发现这个查询部分需要很多负载。我如何优化此 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
)
我认为 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
或类似的东西
我创建了从各种项目(数据库)动态收集一些记录到临时 table 中的过程,然后从那个临时 table 我插入到 table 中。使用 WHERE
statement ,但不幸的是,当我检查执行计划时,我发现这个查询部分需要很多负载。我如何优化此 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
)
我认为 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
或类似的东西