sql查询与不同的表结构相关

时间:2014-01-10 19:01:51

标签: sql sql-server

我有3张桌子,

  • 表A包含列字段idcode_idclaim_id
  • 表B包含列字段idclaim_idmem_idp_id
  • 表C包含idcode_idend_dtorder_idstrt_date

现在,我必须从table A中选择那些不在table b中的claim_d,并在table C中插入这些额外的claim_id。 id是主键。所有表的结构都不同,谁能让我知道怎么做?

我通过以下查询从table A获得了额外的行:

select distinct ad.claim_id 
 FROM tableA a
 left join tableC c 
 on LEFT(c.CLAIM_ID,12) = a.Claim_id 
 where id is not null

然后我不确定如何在tableB ??

中添加这些列

2 个答案:

答案 0 :(得分:0)

根据用户输入,以下是建议的查询:

   declare @outputTable table (id int, claimid varchar(50) not null)

   -- identify values from table A that are not in table B
   ;with cteClaimIdsInAButNotInB
   as
   (
     select
       a.claim_id, a.code_id
     from
       tableA a
       left outer join tableB b on 
           a.claim_id = b.claim_id
     where
       b.claim_id is null
   )

   -- Add these newly found values to tableB and get the id from it
   merge into tableB as b
   using cteClaimIdsInAButNotInB as cte
   on (b.claimid = cte.claimid)
   when not matched then
          insert(claimid) values(cte.claimid)
          output inserted.id, cte.claimid into @outputTable(id, claimid)

   -- Add these newly added values from tableB to tableC as well
   insert into tableC(id, claimid)
   select id, claimid from @outputTable

答案 1 :(得分:0)

只需修改代码即可使用正确的字段...

 ;
    with cteClaimIdsInAButNotInB
       as
       (
           select
               a.claim_id, a.code_id, a.id
           from
               tableA a
               left outer join tableB b on 
                   a.claim_id = b.claim_id
           where
               b.claim_id is null
       )

       insert into tableC (claim_id, code_id)
       select claim_id, code_id from cteClaimIdsInAButNotInB;