Compare two tables and insert all records with added or removed status in 3rd table using SQL Server procedure

后端 未结 5 1534
梦谈多话
梦谈多话 2021-01-27 17:43

I have table A and table B . I have to compare this tables records and insert data to table C using SQL Server procedure in below format

table A

  name
          


        
5条回答
  •  情歌与酒
    2021-01-27 18:14

    You can do this with a full join and conditional logic:

    select 
        coalesce(a.name, b.name) name,
        case
            when a.name is null then 'newly added'
            when b.name is null then 'removed'
        end status
    from tablea a
    full join tableb b on b.name = a.name
    order by name
    

    Demo on DB Fiddle:

    name | status     
    :--- | :----------
    A    | null       
    B    | null       
    C    | null       
    D    | null       
    E    | removed    
    F    | null       
    G    | null       
    Q    | newly added
    

提交回复
热议问题