SQL - 查找表中的差异并插入/更新表缺失值

时间:2014-02-19 19:25:10

标签: sql sql-server

我有一个SQL Server Express数据库,其中包含一个我不想操作的系统生成的表,所以我创建了另一个表。

TABLE_1

AreaName
Area_1       
Area_2
Area_3
Area_4

TABLE_2

Area_1
Area_2
  1. 我想搜索表之间的差异(我已经对它进行了排序)
  2. 与Table_1相比,Table_2中丢失的值应作为新行插入。
  3. 这可以在一个声明中做到吗?

    SELECT 
        MIN (TableName) AS TableName,
        Area 
    FROM 
        (SELECT 
            'Table A' AS TableName, 
            Table_2.Area
         FROM Table_2 
    
         UNION ALL
    
         SELECT 
            'Table B' AS TableName, 
            Area
         FROM [Table_1]) tmp 
    GROUP BY 
       Area
    HAVING 
       COUNT(*) = 1 
    ORDER BY 
       Area;
    

    这是我现在用来排序的SQL ......

2 个答案:

答案 0 :(得分:1)

直截了当的做法:

INSERT INTO Table_2 (AreaName)
SELECT AreaName FROM Table_1
WHERE AreaName NOT IN (SELECT AreaName FROM Table_2)

答案 1 :(得分:0)

Insert into table1 (columns)
select Columns from table2 a
where not exists(select * from table3 b where a.ID =b.ID)