1

I am trying to use MERGE in a procedure and in the insert values I would like to use a query using the USING_SET

The MERGE looks like below:

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));

The error that I got is:

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).

Some how oracle cannot recognize the "src" inside the Subquery. Any ideas?

2 Answers 2

1

you can use a 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;
Sign up to request clarification or add additional context in comments.

Comments

0

you could use subquery in src itself something like below

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);

2 Comments

Yes you are right but I am trying to create this merge with the lowest cost. So I am trying to avoid the subquery in using_set.
post some CREATE scripts and INSERT statements will be useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.