除了 John Woo 的建议之外,这里还有两个选择。
使用左连接
INSERT INTO tbl_Snapshot
SELECT *
FROM @mtts mtts
LEFT JOIN tbl_Snapshot ss ON mtts.MM = ss.MM AND mtts.ProjectID = ss.ProjectID
WHERE ss.MM IS NULL AND ss.tbl_Snapshot IS NULL
使用 Merge 语句(将从 Sql Server 2008 开始工作)
MERGE tbl_Snapshot AS ss
USING (SELECT * FROM @mtts) AS mtts
ON mtts.MM = ss.MM AND mtts.ProjectID = ss.ProjectID
WHEN NOT MATCHED THEN
INSERT([MM],[YYYY],[month_Start],[month_Finish],[ProjectID],[ProjectedBillable],[ProjectedPayable],
[ActualBilled],[ActualPaid],[Total_To_Bill],[Total_To_Pay])
VALUES(mm.[MM],mm.[YYYY],mm.[month_Start],mm.[month_Finish],mm.[ProjectID],mm.[ProjectedBillable],mm.[ProjectedPayable],
mm.[ActualBilled],mm.[ActualPaid],mm.[Total_To_Bill],mm.[Total_To_Pay]);
这是一种非常肮脏的方式(CAST 到 VARCHAR,然后是 MERGE,最后是 COMPARE)
INSERT INTO tbl_Snapshot
SELECT *
FROM @mtts mtts
WHERE CAST(mtts.MM AS vARCHAR(10)) + CAST(mtts.ProjectID AS VARCHAR(10))
NOT IN (SELECT CAST(ss.MM AS vARCHAR(10)) + CAST(ss.ProjectID AS VARCHAR(10)) FROM tbl_Snapshot ss)