2016-09-16 88 views
0

我有兩個表XX_1和XX_MAP_1。結構如下。Oracle SQL更新

XX_1

XX_EMPLOYEE_ID XX_GTN_NBR ERNCD 
00001    21 
00001    23 
00120    34 
00120    37 
00120    23 

XX_MAP_1

XX_GTN  ERNCD 
21   A1 
22   A2 
23   BB1 
34   AB1 

......

我需要能夠與來自XX_MAP_1其中XX_GTN_NBR匹配的值來更新XX_1表(字段ERNCD)匹配

預期結果

XX_EMPLOYEE_ID XX_GTN_NBR ERNCD 
00001    21   A1 
00001    23   BB1 
00120    34   AB1 
00120    37 
00120    23   BB1 

回答

1

在這種情況下,merge是首選解決方案。它已經提供。

下面是使用連接更新語法(根據另一個發佈的答案,「Oracle不支持」)的解決方案。這裏提出不要與merge解決方案競爭,只是爲了表明Oracle確實支持連接更新語法。

這裏是update聲明:

update (select x.erncd as x_erncd, m.erncd as m_erncd 
     from xx_1 x inner join xx_map_1 m on x.xx_gtn_nbr = m.xx_gtn 
     ) 
set x_erncd = m_erncd; 

這裏是一個競爭的會話來說明其工作原理。

create table xx_map_1 (xx_gtn number primary key, erncd varchar2(10)); 

insert into xx_map_1 
    select 21, 'A1' from dual union all 
    select 22, 'A2' from dual union all 
    select 23, 'BB1' from dual union all 
    select 34, 'AB1' from dual 
; 
select * from xx_map_1; 

    XX_GTN ERNCD  
---------- ---------- 
     21 A1   
     22 A2   
     23 BB1  
     34 AB1 

create table xx_1 (xx_employee_id varchar2(20), xx_gtn_nbr number, erncd varchar2(10)); 

insert into xx_1 
    select '00001', 21, null from dual union all 
    select '00001', 23, null from dual union all 
    select '00120', 34, null from dual union all 
    select '00120', 37, null from dual union all 
    select '00120', 23, null from dual 
; 
select * from xx_1; 

XX_EMPLOYEE_ID  XX_GTN_NBR ERNCD  
-------------------- ---------- ---------- 
00001      21   
00001      23   
00120      34   
00120      37   
00120      23 

insert聲明和結果:

update (select x.erncd as x_erncd, m.erncd as m_erncd 
     from xx_1 x inner join xx_map_1 m on x.xx_gtn_nbr = m.xx_gtn 
     ) 
set x_erncd = m_erncd; 

select * from xx_1; 

XX_EMPLOYEE_ID  XX_GTN_NBR ERNCD  
-------------------- ---------- ---------- 
00001      21 A1   
00001      23 BB1  
00120      34 AB1  
00120      37   
00120      23 BB1 
+0

謝謝,合併是答案。 –

2

Oracle不支持加入更新的語法,但你可以使用UPDATE使用子查詢代替:

UPDATE XX_1 t1 
SET ERNCD = (SELECT t2.ERNCD FROM XX_MAP_1 t2 WHERE t2.XX_GTN = t1.XX_GTN_NBR) 
1

使用條款「WHEN MATCHED THEN」只MERGE語句嘗試。

MERGE INTO XX_1 X 
USING XX_MAP_1 XM 
ON (X.XX_GTN_NBR = XM.XX_GTN) 
WHEN MATCHED THEN 
UPDATE SET X.ERNCD = XM.ERNCD;