Oracle:如果不存在则插入或更新不起作用

Oracle: Insert if not exist or Update not working

如果记录不存在,我将尝试插入,否则更新以下 table.However 它说 0 0 行 inserted.But 当我测试我的 select 语句时它返回 1 .

create table tb_coba2 (id number , nis number , nilai_b number , semester number);

查询:

insert into TB_COBA2 (nis , nilai_b , semester)
     select :nis , :nilai_a , :semester
      from dual
      where not exists (
       select 1 from tb_coba2
      where nis = :nis and semester = :semester
      );
      commit;


alter table tb_coba2 add constraint tb_coba2_uq unique ( nis, semester );

以下查询 returns 1 在第一次插入后,但如果我 运行 完全插入,它说插入了 0 条记录。

select 1 个来自 tb_coba2 其中 nis = :nis 和 semester = :semester

我哪里做错了?

您的原始代码执行其预期的操作,即:如果给定的 (nis, semester) 尚不存在于 table 中,则插入该行。

但是,您的问题提到当记录已经存在时您也想更新:

I am trying to insert if the record not exist otherwise update

在 Oracle 中,您可以为此使用 merge 语句。根据您对问题的描述,应该是:

merge into tb_coba2 t
using (select :nis nis, :nilai_a nilai_a, :semester semester from dual) s
on (s.nis = t.nis and s.semester = t.semester)
when matched then update set t.nilai_a = s.nilai_a
when not matched then insert (nis, nilai_a, semester) values (s.nis, s.nilai_a, s.semester)