您的位置:首页 > 数据库 > Oracle

Oracle存在则更新,不存在则插入应用

2014-07-25 22:25 323 查看
更新同一张表的数据。需要注意下细节,因为可能涉及到using的数据集为null,所以要使用count()函数。

MERGE INTO mn a
USING (select count(*) co from mn where mn.ID=4) b
ON (b.co<>0)--这里使用了count和<>,注意下,想下为什么!
WHEN MATCHED THEN
UPDATE
SET a.NAME = 'E'
where a.ID=4
WHEN NOT MATCHED THEN
INSERT
VALUES (4, 'E');


不同表:

--测试数据
create table table1(id varchar2(100),name varchar2(1000),address varchar2(1000));
insert into table1(id,name,address)values('01001','影子','河北') ;
commit;

--插入
merge into table1 t1
using (select '01002' id,'影子' name,'河北' address from dual) t2
on (t1.id = t2.id)
when matched then
update set t1.name = t2.name, t1.address = t2.address
when not matched then
insert values (t2.id, t2.name,t2.address);
commit;

--查询结果
select * from table1
01001    影子    河北
01002    影子2    辽宁

--更新
merge into table1 t1
using (select '01001' id,'不是影子' name,'山西' address from dual) t2
on (t1.id = t2.id)
when matched then
update set t1.name = t2.name, t1.address = t2.address
when not matched then
insert values (t2.id, t2.name,t2.address);
commit;

--查询结果
select * from table1

01001    不是影子    山西
01002    影子2    辽宁

--删除测试数据
drop table table1;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: