问题描述
我有一张表:
其中包含以下数据:
现在我想插入一条记录,但是如果ID在表中已经就绪,我想要一个更新。
所以如果我这样做插入
我希望触发器进行更新而不是插入。
触发器可能是这样的:
但是我不知道如何创建此触发器。
create table test_tbl (id number, text varchar2(50));
其中包含以下数据:
insert into test_tbl values (1,'Text 1'); insert into test_tbl values (2,'Text 2');
现在我想插入一条记录,但是如果ID在表中已经就绪,我想要一个更新。
所以如果我这样做插入
insert into test_tbl values (2,'Text 2 edited');
我希望触发器进行更新而不是插入。
触发器可能是这样的:
create trigger test_trg
before insert on test_tbl for each row
begin
if exists (select * from test_tbl where id = :new.id) then
-- update record
else
-- insert into table
end if;
end;但是我不知道如何创建此触发器。
专家解答
不要为此使用触发器。麻烦比它值得的多。在这个网站上搜索 “阅读一致性” 和 “变异表”,以获得多么复杂的例子。
最佳分辨率:
1) 添加一个约束,
2) 使用合并来处理插入和更新
最佳分辨率:
1) 添加一个约束,
alter table test_tbl add primary key ( id )
2) 使用合并来处理插入和更新
merge into test_tbl t using ( select [new values] from dual ) n on ( t.id = n.id) when matched then update set t.col = n.col, etc when not matched than insert (t.id,t.col, ... ) values (n.id,n.col, ... )
文章转载自ASKTOM,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




