0

我有两个表,一个是临时表,另一个是数据库表。我需要根据 MM 和 ProjectID 比较两个表。如果数据存在于 @mtts 但不存在于 tbl_snapshot 中,那么我必须将其插入 tbl_sanpshot

@mtts 表([MM],[YYYY],[month_Start],[month_Finish],[ProjectID],[ProjectedBillable],[ProjectedPayable],[ActualBilled],[ActualPaid],[Total_To_Bill],[Total_To_Pay])

tbl_Snapshot ([MM],[YYYY],[month_Start],[month_Finish],[ProjectID],[ProjectedBillable],[ProjectedPayable],[ActualBilled],[ActualPaid],[Total_To_Bill],[Total_To_Pay])。

我是 sql.so 的新手,所以请帮助我

4

3 回答 3

1

您可以使用INSERT INTO...SELECTandEXISTS来解决您的问题,试试这个

INSERT INTO tbl_Snapshot([MM],[YYYY],[month_Start],[month_Finish],
                         [ProjectID],[ProjectedBillable],[ProjectedPayable],
                         [ActualBilled],[ActualPaid],[Total_To_Bill],
                         [Total_To_Pay])
SELECT *
FROM mtts
WHERE NOT EXISTS (SELECT * FROM tbl_Snapshot)
于 2012-09-10T00:57:56.630 回答
1

除了 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)
于 2012-09-10T03:21:09.943 回答
0

尝试这个 ,

插入 tbl_Snapshot select * from @mtts where [MM] not in(select [MM] from tbl_Snapshot) and [ProjectID] not in (select [ProjectID] from tbl_Snapshot)

谢谢,

文卡特

于 2012-09-10T06:25:49.100 回答