您可以使用 MERGE 语句。除其他外,它允许一个简单的 UPSERT(它实际上允许对 SET 行进行 UPSERT,而不仅仅是单行)。考虑:
SQL> CREATE TABLE TEST (
2 ID NUMBER,
3 a VARCHAR2(10),
4 b VARCHAR2(10),
5 CONSTRAINT pk_test PRIMARY KEY (ID)
6 );
Table created
SQL> MERGE INTO TEST t
2 USING (SELECT 1 ID, 'a' a, 'b' b FROM dual) new_row
3 ON (t.id = new_row.id)
4 WHEN MATCHED THEN
5 UPDATE SET t.a = new_row.a,
6 t.b = new_row.b
7 WHEN NOT MATCHED THEN
8 INSERT (ID, a, b) VALUES (new_row.id, new_row.a, new_row.b);
Done
SQL> SELECT * FROM TEST;
ID A B
---------- ---------- ----------
1 a b
SQL> MERGE INTO TEST t
2 USING (SELECT 1 ID, 'x' a, 'y' b FROM dual) new_row
3 ON (t.id = new_row.id)
4 WHEN MATCHED THEN
5 UPDATE SET t.a = new_row.a,
6 t.b = new_row.b
7 WHEN NOT MATCHED THEN
8 INSERT (ID, a, b) VALUES (new_row.id, new_row.a, new_row.b);
Done
SQL> SELECT * FROM TEST;
ID A B
---------- ---------- ----------
1 x y
即:您可以使用相同的语句插入和更新。
干杯,
——
文森特