且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

比较两个表,并使用SQL Server过程在第3个表中插入具有添加或删除状态的所有记录

更新时间:2023-12-01 10:57:28

根据您最终要完成的顺序,可以使用以下命令:

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);

然后,如果要按表a中的顺序进行排序,则首先选择from b left join a,在第二个中选择from a left join b,如果要根据表b中的情况进行排序,请首先选择选择from a left join b,然后第二个选择from b left join a.

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.