如何插入不匹配现有行以及更新非现有行

时间:2016-06-24 10:31:52

标签: sql sql-server

我有两个相同结构的表T1T2如下,IDFilename组合在两个表中标识Unique ROW

       T1                                         T2
ID  FileName  IsActive             ID   FileName  IsActive

现在我想在两个不同的场景中编写两个不同的查询

情景1

Row exist T1 but not in T2  
in this scenario insert the rows which exist in T1 but not in T2

情景2

ROW Doest not exist in T1 but exist in T2 
in this scenario update T2 set IsActive of that rows as 0

IDFilename组合在两个表格中都标识了Unique ROW

编写查询的任何帮助?

1 个答案:

答案 0 :(得分:0)

第一次查询:

INSERT INTO T2 (ID, FileName, IsActive)
SELECT T1.ID, T1.FileName, T1.IsActive
FROM T1 LEFT JOIN T2
     ON T1.ID = T2.ID AND T1.FileName = T2.FileName
WHERE T2.ID IS NULL

第二次查询:

UPDATE T2
SET T2.IsActive = 0
FROM T2 LEFT JOIN T1
     ON T2.ID = T1.ID AND T2.FileName = T1.FileName
WHERE T1.ID IS NULL