同一张表的合并语句不会插入新行,而是更新Oracle DB中的现有行

时间:2018-09-18 14:22:16

标签: sql database oracle oracle12c sql-merge

我正在尝试使用名为MERGE的Oracle 12 DB表上的CONFIG语句进行upsert操作,

id | name | value

如果存在带有name'NON_TAXABLE_CODE'的行,请将value更新为'400',否则将新行插入其中。

首次尝试

MERGE into CONFIG dest USING (SELECT id, name, value from CONFIG where name = 'NON_TAXABLE_CODE') src
    ON (dest.name = src.name)
WHEN MATCHED THEN
    UPDATE SET dest.value = src.value
WHEN NOT MATCHED THEN
    INSERT (id, name, value) VALUES (src.id, src.name, src.value )

如果该行存在,它将更新该值,但不会插入新行(如果不存在任何行)

第二次尝试:

MERGE into CONFIG as dest USING VALUES (0, 'NON_TAXABLE_CODE', '400') as src (id, name, value)
    ON dest.name = src.name
WHEN MATCHED THEN
    UPDATE SET dest.value = src.value
WHEN NOT MATCHED THEN
    INSERT (id, name, value) VALUES (src.id, src.name, src.value )


Error report -
SQL Error: ORA-02012: missing USING keyword
02012. 00000 -  "missing USING keyword"
*Cause:    
*Action:

第三次尝试:

MERGE into CONFIG as dest USING (select 0 as id, 'VERTEX_PRODTYPE_NON_TAXABLE' as name, '400' as value from DUAL) as src
    ON dest.name = src.name
WHEN MATCHED THEN
    UPDATE SET dest.value = src.value
WHEN NOT MATCHED THEN
    INSERT (id, name, value) VALUES (src.id, src.name, src.value )

Error report -
SQL Error: ORA-02012: missing USING keyword
02012. 00000 -  "missing USING keyword"
*Cause:    
*Action:

有人可以告诉我我在哪里错了吗? 谢谢。

1 个答案:

答案 0 :(得分:4)

问题是,如果不满足where子句,则src中的select不会返回任何行。因此,当条件失败时,它将既不进行更新也不进行插入。

为避免这种情况,您可以从对偶表中选择值。

MERGE INTO config dest USING (
     SELECT 100 AS id,
            'NON_TAXABLE_CODE' AS name,
            400 AS value
     FROM dual
)
src ON ( dest.name = src.name )
WHEN MATCHED THEN UPDATE SET dest.value = src.value
WHEN NOT MATCHED THEN INSERT (
     id,
     name,
     value ) VALUES (
     src.id,
     src.name,
     src.value );

这将在名称匹配时更新行,但在不匹配时插入从对偶中选择的硬编码值。

DB Fiddle Demo