51
insert into OPT (email, campaign_id) values('mom@cox.net',100)
where not exists( select * from OPT where (email ="mom@cox.net" and campaign_id =100)) ;

错误报告:SQL 错误:ORA-00933:SQL 命令未正确结束 00933. 00000 - “SQL 命令未正确结束” *原因:
*操作:

如果 Oracle 中不存在新行,如何插入新行?

4

5 回答 5

93
insert into OPT (email, campaign_id) 
select 'mom@cox.net',100
from dual
where not exists(select * 
                 from OPT 
                 where (email ='mom@cox.net' and campaign_id =100));
于 2013-05-19T22:01:44.400 回答
24

根据已经存在的另一条记录插入某些内容(在 Oracle 中)的正确方法是使用MERGE语句。

请注意,这个问题已经在这里回答了 SO:

于 2012-05-31T08:17:50.437 回答
10
MERGE INTO OPT
USING
    (SELECT 1 "one" FROM dual) 
ON
    (OPT.email= 'mom@cox.net' and OPT.campaign_id= 100) 
WHEN NOT matched THEN
INSERT (email, campaign_id)
VALUES ('mom@cox.net',100) 
;
于 2018-10-22T07:12:04.373 回答
7
insert into OPT       (email,        campaign_id) 
select 'mom@coxnet' as email, 100 as campaign_id from dual MINUS
select                 email,        campaign_id from OPT;

如果OPT中已经有一条带有mom@cox.net/的记录,则将从记录中减去该记录,并且不会插入任何内容。另一方面,如果没有这样的记录,则不会减去任何内容并且值/将被插入。100MINUSselect 'mom@coxnet' as email, 100 as campaign_id from dualMINUSmom@coxnet100

正如p.marino已经指出的那样,merge它可能是解决您的问题的更好(和更正确)的解决方案,因为它是专门为解决您的任务而设计的。

于 2013-05-19T22:01:49.980 回答
0

另一种方法是利用INSERT ALLoracle 的语法,

INSERT ALL 
    INTO table1(email, campaign_id) VALUES (email, campaign_id)
WITH source_data AS
 (SELECT 'mom@cox.net' email,100 campaign_id
  FROM   dual
  UNION ALL
  SELECT 'dad@cox.com' email,200 campaign_id
  FROM   dual)      
SELECT email
      ,campaign_id
FROM   source_data src
WHERE  NOT EXISTS (SELECT 1
        FROM   table1 dest
        WHERE  src.email = dest.email
        AND    src.campaign_id = dest.campaign_id);

INSERT ALL 还允许我们基于作为源的子查询对多个表执行条件插入

有一些非常干净和很好的例子可供参考。

  1. oracletutorial.com
  2. oracle-base.com/
于 2020-08-07T10:50:11.133 回答