一种选择是使用MERGE。这是一个例子。先上样表:
SQL> create table table_a
2 (id number,
3 username varchar2(10),
4 col varchar2(1)
5 );
Table created.
让我们看看它是如何工作的:
SQL> merge into table_a a
2 using (select 1 id,
3 'userX' username,
4 'x' col
5 from dual
6 ) x
7 on (a.id = x.id)
8 when not matched then insert (id, username, col)
9 values (x.id, x.username, x.col);
1 row merged.
SQL> select * From table_a;
ID USERNAME C
---------- ---------- -
1 userX x
好的,userX 已插入。如果我再次尝试插入会怎样?
SQL> merge into table_a a
2 using (select 1 id,
3 'userX' username,
4 'x' col
5 from dual
6 ) x
7 on (a.id = x.id)
8 when not matched then insert (id, username, col)
9 values (x.id, x.username, x.col);
0 rows merged. --> nothing happened
SQL> select * from table_a;
ID USERNAME C
---------- ---------- -
1 userX x
什么也没发生; 0 行合并。
如果我尝试使用 userY 会发生什么?
SQL> merge into table_a a
2 using (select 2 id,
3 'userY' username, --> userY is here
4 'y' col
5 from dual
6 ) x
7 on (a.id = x.id)
8 when not matched then insert (id, username, col)
9 values (x.id, x.username, x.col);
1 row merged. --> 1 row merged
SQL> select * from table_a;
ID USERNAME C
---------- ---------- -
1 userX x
2 userY y
SQL>
结果显示userX 和userY 现在都在表中。