SQLDeveloper:如果不存在则插入

SQLDeveloper: Insert if not exists

我找到了几篇关于在记录不存在时如何插入的帖子,但我不知道为什么我无法让它工作。我总是收到错误消息。

在 SQLDeveloper 中,我只想运行下面的查询:

INSERT INTO TABLE_A VALUES(1, 'userX', 'x', 'y', 'z')

如果已经没有 userX 的记录,即如果以下 select 语句没有 return 任何内容:

SELECT * FROM TABLE_A where user = 'userX'

谢谢

一种选择是使用 MERGE。这是一个例子。示例 table 首先:

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

OK,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>

结果显示 userXuserY 现在都在 table.