Oracle存在則更新,不存在則插入應用

2021-06-22 22:34:17 字數 1449 閱讀 3436

更新同一張表的資料。需要注意下細節,因為可能涉及到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;

Oracle存在則更新,不存在則插入應用

更新同一張表的資料。需要注意下細節,因為可能涉及到using的資料集為null,所以要使用count 函式。sql view plain copy merge into mn a using select count co from mn where mn.id 4 b on b.co 0 這裡使用...

MySQL記錄存在則更新,不存在則插入

create table tb file authorize authorize id int 11 not null auto increment,str id int 11 default null comment 使用者標識 file id int 11 default null commen...

MySql 不存在則插入,存在則更新或忽略

前言 在插入資料時,可能需要忽略或替換掉重複的資料 依據某個字段 這時可以在應用層處理,也可以使用複雜的 sql 語句來處理 如果僅僅知道一些簡單的 sql 語法的話 當然也可以使用一些簡單的 sql 語法,不過它並不是通用所有的資料庫型別。以下所有例項僅針對mysql而言,並不能隨意用於其它資料庫...