[英]sql query related with different table structure
I have 3 tables, 我有3张桌子
id
, code_id
, claim_id
, id
, code_id
, claim_id
表A id
, claim_id
, mem_id
and p_id
, id
, claim_id
, mem_id
和p_id
, id
, code_id
, end_dt
, order_id
, strt_date
. id
, code_id
, end_dt
, order_id
, strt_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.