美文网首页
oracle中利用trigger对表进行有条件的新增或者修改

oracle中利用trigger对表进行有条件的新增或者修改

作者: 清_晨_ | 来源:发表于2018-12-12 17:51 被阅读11次

今天在项目中遇到一个涉及到数据来源的问题,需要根据数据来源进行筛选,如果满足某一条件就进行新增或者更新,如果不满足就不插入。记录一下,方便以后使用。

代码如下:

create or replace trigger person_base_info_trigger
  before insert or update on t_person_base_info    ---before代表在数据插入之前,也可以用after,代表在数据插入之后
  for each row
declare
  pragma autonomous_transaction;
  v_cid              varchar2(32) := :new.c_id; -- 保存更新或修改行的主键
  v_count            number(10); -- 临时表 send_data_tmp 中 相同数据的记录数
  v_idno             varchar2(18) := :new.id_no; -- 身份证号码
  v_health_record_id varchar2(32) := :new.c_id;  
  v_special_crowd    varchar2(128) := :new.special_crowd; -- 特殊人群标记
begin
  if (regexp_count(v_special_crowd, '13', 1, 'i') = 0 and
     regexp_count(v_special_crowd, '14', 1, 'i') = 0) or v_idno is null then
    return;
  end if;
  if :new.sourceflag = '该条数据来源于医院接口' then
    :new.sourceflag := '来源于医院接口';
    return;
  end if;
  select count(*)
    into v_count
    from send_data_tmp
   where tradeno = '0401'
     and pk = v_cid;
  if v_count = 0 then
    -- 如果临时表 send_data_tmp 中与该数据相同的记录数为 0,则插入该条数据。
    insert into send_data_tmp
    values
      ('0401', v_cid, v_idno, v_health_record_id);
    commit;
  end if;
exception
  when others then
    rollback;
    commit;
end;

PS:
insert或者update的时候:我们可以根据数据来源进行刷选,在本例中,

if :new.sourceflag = '该条数据来源于医院接口' then
:new.sourceflag := '来源于医院接口';
return;
end if;

表示,如果在新增或者更新数据的时候,sourceflag 字段的值是“该条数据来源于医院接口”,那么将这条记录中的sourceflag 字段更新为“来源于医院接口”,接着插入到表中,然后退出trigger,程序不会再往下执行。数据库表中sourceflag 字段最后的值为“来源于医院接口”;

如果在新增或者更新的时候,sourceflag 字段不为(该条数据来源于医院接口),那么trigger中的代码接着会往下执行,最后将这条记录的相关信息插入到send_data_tmp这张临时表中,方便我们使用。

注:trigger中:new.字段 和:old.字段 的区别:

相关文章

网友评论

      本文标题:oracle中利用trigger对表进行有条件的新增或者修改

      本文链接:https://www.haomeiwen.com/subject/dhephqtx.html