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中不存在新行,如何插入新行?
答案 0 :(得分:53)
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));
答案 1 :(得分:13)
根据已存在的另一条记录插入内容(在Oracle中)的正确方法是使用MERGE语句。
请注意,此问题已经在SO上得到了解答:
答案 2 :(得分:6)
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
/ 100
的记录,MINUS
将从select 'mom@coxnet' as email, 100 as campaign_id from dual
记录中减去此记录,并且不会插入任何内容。另一方面,如果没有此类记录,则MINUS
不会删除任何内容,并且会插入值mom@coxnet
/ 100
。
正如 p.marino 已经指出的那样,merge
可能是更好(更正确)的解决方案,因为它专门用于解决您的任务。
答案 3 :(得分:2)
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)
;
答案 4 :(得分:0)
另一种方法是利用oracle的INSERT ALL
语法,
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
还允许我们基于作为源的子查询对多个表执行条件插入。
这里有一些非常干净和不错的示例可供参考。