Using MERGE is your best bet. You can control each of the conditions. WHEN MATCHED THEN, WHEN UNMATCHED THEN etc.
MERGE - Technet
MERGE- MSDN (GOOD!)
Example A: Transactional usage - Table Variables - NO
DECLARE @Source TABLE (ID INT)
DECLARE @Target TABLE (ID INT)
INSERT INTO @Source (ID) VALUES (1),(2),(3),(4),(5)
BEGIN TRANSACTION
MERGE @Target AS T
USING @Source AS S
ON (S.ID = T.ID)
WHEN NOT MATCHED THEN
INSERT (ID) VALUES (S.ID);
ROLLBACK TRANSACTION
SELECT 'FAIL' AS Test,*
FROM @Target
Example B: Transactional usage - Physical Tables
CREATE TABLE SRC (ID INT);
CREATE TABLE TRG (ID INT);
INSERT INTO SRC (ID) VALUES (1),(2),(3),(4),(5)
BEGIN TRANSACTION
MERGE TRG AS T
USING SRC AS S
ON (S.ID = T.ID)
WHEN NOT MATCHED THEN
INSERT (ID) VALUES (S.ID);
ROLLBACK TRANSACTION
SELECT 'FAIL' AS Test,*
FROM TRG
Example C: Transactional usage - Tempdb (local & global)
CREATE TABLE #SRC (ID INT);
CREATE TABLE #TRG (ID INT);
INSERT INTO #SRC (ID) VALUES (1),(2),(3),(4),(5)
BEGIN TRANSACTION
MERGE #TRG AS T
USING #SRC AS S
ON (S.ID = T.ID)
WHEN NOT MATCHED THEN
INSERT (ID) VALUES (S.ID);
ROLLBACK TRANSACTION
SELECT 'FAIL' AS Test,*
FROM #TRG
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…