Update_or_insert(合并到)在Oracle中不起作用

时间:2012-09-26 08:21:43

标签: oracle join oracle11g insert-update

我的UPDATE_OR_INSERT代码有什么问题?

MERGE INTO EMAIL_LIST d USING (SELECT 'foo@gmail.com' EMAIL) s
    ON (d.EMAIL = s.EMAIL)
        WHEN MATCHED THEN
            UPDATE SET d.EMAIL = s.EMAIL
        WHEN NOT MATCHED THEN
            INSERT (EMAIL) VALUES (s.EMAIL);

鉴于表格:

CREATE TABLE EMAIL_LIST ( 
    EMAIL VARCHAR2 (100)  NOT NULL
);
ALTER TABLE EMAIL_LIST
    ADD CONSTRAINT PK_EMAIL_LIST PRIMARY KEY ( EMAIL ) ;

错误

  

错误报告:

     

SQL错误:ORA-00923:找不到FROM关键字   00923. 00000 - “找不到FROM关键字”

1 个答案:

答案 0 :(得分:4)

有几件事;

你需要从某些东西中选择常量,在Oracle的情况下,DUAL;

MERGE INTO EMAIL_LIST d 
USING 
    (SELECT 'foo@gmail.com' EMAIL FROM DUAL) s
ON (d.EMAIL = s.EMAIL)
WHEN MATCHED THEN
    UPDATE SET d.EMAIL = s.EMAIL
WHEN NOT MATCHED THEN
    INSERT (EMAIL) VALUES (s.EMAIL);

此外,您无法在d.EMAIL上进行匹配,同时也会对其进行更新。你的路线;

WHEN MATCHED THEN
    UPDATE SET d.EMAIL = s.EMAIL

无论如何都没有意义,因为d.EMAIL已经等于s.EMAIL或匹配不会发生。移除WHEN MATCHED,您将最终完成工作;

MERGE INTO EMAIL_LIST d 
USING 
    (SELECT 'foo@gmail.com' EMAIL FROM DUAL) s
ON (d.EMAIL = s.EMAIL)
WHEN NOT MATCHED THEN
    INSERT (EMAIL) VALUES (s.EMAIL);