我有3张桌子,
id
,code_id
,claim_id
,id
,claim_id
,mem_id
和p_id
,id
,code_id
,end_dt
,order_id
,strt_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
??
答案 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;