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

Oracle 11g merge Invalid Identifier with subquery in the INSERT VALUES

我正在尝试在过程和插入值中使用 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));

我得到的错误是:

invalid SQL Error: ORA-00904: "SRC"."CUSTOMER_ID": invalid identifier in the subquery (select count(f.FOO_ID) from S_FOO f where f.CUSTOMER_ID = src.CUSTOMER_ID).

有些 oracle 无法识别子查询中的 "src"。有什么想法吗?

您可以在 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);

你可以使用 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;