I'm trying to use MERGE for an UPSERT. The update code works well (I haven't posted here) with this MERGE statement but INSERT is giving the following errors:
Basically I want to write the MERGE-INSERT statement that accommodates the DECODE statement as well. Please help me as I'm new to Oracle.
MERGE INTO Table1 t1
USING(SELECT DISTINCT A_cd, F_str, a_pm, a_type
FROM Table2) t2
ON(t1.C_Name=t2.A_cd)
WHEN NOT MATCHED
THEN
INSERT(C_type, C_name, C_value)
VALUES (SELECT t3.C_type, t4.A_cd as C_name,
DECODE(t3.c_type,
'A COMP', t4.f_str,
'A_PM', t4.a_pm,
'A_TYPE' t4.a_type) as c_value)
FROM(SELECT 'A_COMP' as c_type FROM DUAL
UNION ALL
SELECT 'A_PM' as c_type FROM DUAL
UNION ALL
SELECT 'A_TYPE' as c_type FROM DUAL)t3,
(SELECT DISTINCT A_cd, F_str, a_pm, a_type
FROM Table2 t2
WHERE A_cd || F_str || a_pm || a_type
IS NOT NULL
AND NOT EXISTS
(SELECT NULL
FROM Table1 t1
WHERE t2.A_cd=t1.c_name))t4;
You can't use select statement while inserting using merge,so for values you have to use your select statement after 'using' keyword and then passing the value of select into the insert statement .
MERGE INTO Table1 t1
USING (SELECT t3.C_type, t4.A_cd as C_name,
DECODE(t3.c_type,
'A COMP', t4.f_str,
'A_PM', t4.a_pm,
'A_TYPE' t4.a_type) as c_value)
FROM(SELECT 'A_COMP' as c_type FROM DUAL
UNION ALL
SELECT 'A_PM' as c_type FROM DUAL
UNION ALL
SELECT 'A_TYPE' as c_type FROM DUAL)t3,
(SELECT DISTINCT A_cd, F_str, a_pm, a_type
FROM Table2 t2
WHERE A_cd || F_str || a_pm || a_type
IS NOT NULL
AND NOT EXISTS
(SELECT NULL
FROM Table1 t1
WHERE t2.A_cd=t1.c_name))t4
ON(t1.C_Name=t4.A_cd)
WHEN NOT MATCHED
THEN
INSERT(C_type, C_name, C_value)
values(t4.C_type, t4.C_name,t4.c_value);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.