简体   繁体   English

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

[英]sql query related with different table structure

I have 3 tables, 我有3张桌子

  • table A with column fields id , code_id , claim_id , 具有列字段idcode_idclaim_id表A
  • table B with column fields id , claim_id , mem_id and p_id , 表B具有列字段idclaim_idmem_idp_id
  • table C with id , code_id , end_dt , order_id , strt_date . 具有idcode_idend_dtorder_idstrt_date表C。

Now i have to select those claim_d from table A which are not in table b and insert those additional claim_id in table C . 现在,我必须从table A选择不在table b那些Claim_d并将那些其他的Claim_id插入table C id is the primary key.structure for all table is different, can anyone let me know how to do this?? id是主键。所有表的结构都不同,有人可以让我知道怎么做吗?

i got the additional rows from table A by following query: 我通过以下查询从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

then I am not sure how to add those columns in tableB ?? 那么我不确定如何在tableB添加这些列?

Based on the user input, following is the proposed query: 根据用户输入,以下是建议的查询:

   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

Just modify the code to use the correct fields ... 只需修改代码即可使用正确的字段...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM