有时有这样的需求,我们在对数据库插入时,可能会插入重复的数据,但是又不想

修改现有的程序,我们可以使用触发器来避免修改程序,直接在数据库中解决问题。

测试步骤:

1.首先我们创建一个测试的数据库表。

 

CREATE TABLE "GZRDYA"."TBTEST" 
   (    "ID" 
NUMBER(13,0), 
    "NAME" NVARCHAR2(
200)
   ) 

 

2.创建一个触发器。

检测ID是否重复,若有重复,则抛出错误,不插入数据。

 

代码
create or replace trigger trig_tbtest
before 
insert on tbtest for each row
declare
v_count 
number(5);
begin
select count(*into v_count from tbtest where id=:new.id;
if (v_count>0then
    raise_application_error(
-20000,'data is duplication');
end if;
end;

 

 

3.做测试

尝试插入重复的ID数据,发现数据不能插入,且抛出错误。

 

 

相关文章:

  • 2021-11-06
  • 2021-06-24
  • 2021-05-11
  • 2021-12-12
  • 2021-06-02
  • 2022-01-20
  • 2022-12-23
  • 2021-12-01
猜你喜欢
  • 2021-06-09
  • 2022-12-23
  • 2021-11-02
  • 2021-07-30
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案