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

后端 未结 5 1590
梦谈多话
梦谈多话 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 17:50

    Depending on which order do you want to accomplish at the end you can use this:

    select name, max(status), descr from(
    select 
        coalesce(a.col, b.col) name,
        coalesce(a.descr, b.descr) descr,
        case
            when a.col is null then 'newly added'
            when b.col is null then 'removed'
        end status
        , ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) rn
    from a a
    left join b b on b.col = a.col
    union
    select 
        coalesce(a.col, b.col) name,
        coalesce(a.descr, b.descr) descr,
        case
            when a.col is null then 'newly added'
            when b.col is null then 'removed'
        end status
        , ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) rn
    from b b
    left join a a on b.col = a.col) A
    group by name, descr
    order by max(rn);
    

    And then if you want to order by how it is in table a then in first select select from b left join a and in your second select from a left join b and if you want to oder by how it is in table b then in first select select from a left join b and in your second select from b left join a.

    Here is a demo with the last requested samle data.

提交回复
热议问题