【问题标题】:SQLDeveloper: Insert if not existsSQLDeveloper:如果不存在则插入
【发布时间】:2020-07-22 12:34:43
【问题描述】:

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

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

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

如果 userX 已经没有记录,那就是如果下面的 select 语句没有返回任何内容:

SELECT * FROM TABLE_A where user = 'userX'

谢谢

【问题讨论】:

  • 请描述您的TABLE_A数据结构,然后我们可以分析错误原因

标签: sql oracle oracle-sqldeveloper sql-insert


【解决方案1】:

一种选择是使用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>

结果显示userXuserY 现在都在表中。

【讨论】:

    猜你喜欢
    • 2018-09-17
    • 2014-06-11
    • 1970-01-01
    • 2017-04-24
    • 1970-01-01
    • 2016-05-15
    • 1970-01-01
    • 2015-03-31
    • 1970-01-01
    相关资源
    最近更新 更多