Oracle触发器 - 更新行应根据条件更新同一表中的多个行

时间:2016-06-07 11:27:30

标签: oracle database-trigger

我已根据记录更新的值

编写了一个触发器来更新(之前)表中的记录
CREATE OR REPLACE TRIGGER CONTACTS_UPDATE_TRIGGER 
BEFORE UPDATE  ON CONTACTS 
FOR EACH ROW 
BEGIN 
IF :NEW.CONTACT_TYPE= 'PRIMARY' THEN  
UPDATE CONTACTS SET CONTACT_TYPE= NULL WHERE CONTACT_TYPE = 'PRIMARY' AND HOSPITAL_ID = :NEW.HOSPITAL_ID ;
END IF;
END;

但是得到表变异错误。是否有其他方法可以根据oracle db

中更新的行中的值更新表中的其他行

1 个答案:

答案 0 :(得分:1)

如果我是你,而不是触发器,我会修改原始更新语句(最好是在一个存储过程中,这是唯一可以更新表,但是hey-ho,YMMV),如下所示:

update contacts
set    contact_type= case when contact_type = 'PRIMARY' then null
                          when hospital_id = :hospital_id then 'PRIMARY'
                     end
where  contact_type = 'PRIMARY'
or     hospital_id = :hospital_id;

这是一个测试用例:

<强>设置

create table contacts (hospital_id number,
                       contact_type varchar2(10),
                       val number);

insert into contacts (hospital_id, contact_type, val)
select 1, 'PRIMARY', 100 from dual union all
select 2, null, 200 from dual union all
select 3, null, 300 from dual;

commit;

select * from contacts
order by hospital_id;

HOSPITAL_ID CONTACT_TYPE        VAL
----------- ------------ ----------
          1 PRIMARY             100
          2                     200
          3                     300

更新主要医院

update contacts
set    contact_type= case when contact_type = 'PRIMARY' then null
                          when hospital_id = 3 then 'PRIMARY'
                     end
where  contact_type = 'PRIMARY'
or     hospital_id = 3;

commit;

<强>结果

select * from contacts
order by hospital_id;

HOSPITAL_ID CONTACT_TYPE        VAL
----------- ------------ ----------
          1                     100
          2                     200
          3 PRIMARY             300