日期:2014-05-17  浏览次数:20789 次

一条插入语句,求大神帮忙



有一张表A 
a1 a2 a3

一张表B
b1 b2 b3 b4

一张表C

c1 c2 c3 c4

一张表D
d1 d2 d3 d4 d5 来源表名

现在的需求是 
表B同A比对,当b.b2=a.a2时取表B的部分字段插入表D并在来源表名那列标注区分是哪个表来的数据
表C同A比对,当c.b2=a.a2时取表C的部分字段插入表D并在来源表名那列标注区分是哪个表来的数据

能一个语句搞定吗,或者一个存储过程

------解决方案--------------------
引用:
忘了写上,不能插入重复数据,你这个会报违反唯一约束



insert into d
  (d1, d2, d3, d4, d5, 来源表名)
  select *
    from (select b1, b2, b3, b4, null b5, 'B' b6
            from b
           where exists (select 1 from a where a.a2 = b.b2)
          union
          select c1, c2, c3, c4, null, 'C'
            from c
           where exists (select 1 from a where a.a2 = c.c2)) t
   where not exists (select 1
            from d
           where d1 = t.b1
             and d2 = t.b2
             and d3 = t.b3
             and d4 = t.b4
             and 来源表名 = t.b6)