Oracle 11g在INSERT VALUES中将子查询与无效标识符合并

时间:2015-03-05 09:48:51

标签: sql oracle plsql oracle11g merge

我正在尝试在过程中使用MERGE,在插入值中我想使用USING_SET

的查询

MERGE如下所示:

MERGE INTO N_CUSTOMER dest
   USING S_customer src 
    ON (dest.CUSTOMER_ID = src.CUSTOMER_ID)
    WHEN
     MATCHED THEN
     update set
     dest.DATE_OF_BIRTH = src.S_BIRTHDATE,
     dest.GENDER = src.S_GENDER,
     dest.NAME = src.S_NAME
     WHEN NOT MATCHED THEN
     INSERT (DATE_OF_BIRTH, GENDER, NAME, TOTAL_FOO_COUNT)
     VALUES (src.S_BIRTHDATE, src.S_GENDER, src.S_NAME, 
            (select count(f.FOO_ID) from S_FOO f where f.CUSTOMER_ID = src.CUSTOMER_ID));

我得到的错误是:

  

无效的SQL错误:ORA-00904:“SRC”。“CUSTOMER_ID”:子查询中的标识符无效(从S_FOO f中选择count(f.FOO_ID),其中f.CUSTOMER_ID = src.CUSTOMER_ID)。

oracle如何识别子查询中的“src”。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

您可以使用outer variable

declare 
o_variable number;

begin

select count(f.FOO_ID) 
into o_variable 
from S_FOO f where f.CUSTOMER_ID in (select CUSTOMER_ID from S_customer.CUSTOMER_ID);

MERGE INTO N_CUSTOMER dest
   USING S_customer src 
    ON (dest.CUSTOMER_ID = src.CUSTOMER_ID)
    WHEN
     MATCHED THEN
     update set
     dest.DATE_OF_BIRTH = src.S_BIRTHDATE,
     dest.GENDER = src.S_GENDER,
     dest.NAME = src.S_NAME
     WHEN NOT MATCHED THEN
     INSERT (DATE_OF_BIRTH, GENDER, NAME, TOTAL_FOO_COUNT)
     VALUES (src.S_BIRTHDATE, src.S_GENDER, src.S_NAME,o_variable);
end;

答案 1 :(得分:0)

你可以在src中使用子查询,如下所示

MERGE INTO N_CUSTOMER dest
   USING 
    (
    select cus.*,k.cnt
    S_customer cus join
    (select count(f.FOO_ID) cnt ,CUSTOMER_ID 
        from S_FOO f group by CUSTOMER_ID ) k
    on cus.CUSTOMER_ID = k.CUSTOMER_ID 
    ) src 
    ON (dest.CUSTOMER_ID = src.CUSTOMER_ID)
    WHEN
     MATCHED THEN
     update set
     dest.DATE_OF_BIRTH = src.S_BIRTHDATE,
     dest.GENDER = src.S_GENDER,
     dest.NAME = src.S_NAME
     WHEN NOT MATCHED THEN
     INSERT (DATE_OF_BIRTH, GENDER, NAME, TOTAL_FOO_COUNT)
     VALUES (src.S_BIRTHDATE, src.S_GENDER, src.S_NAME, src.cnt);