如果记录存在则插入触发器 - Oracle

时间:2021-04-17 06:35:04

标签: oracle triggers

我有桌子:

DEPARTMETS 带有 dep_id(number)、dep_name(varchar)、manager_id(number) 字段。

EMPLOYEES with employee_id(number)、name(varchar)、salary(number)、manager_id(number)

我想创建一个触发器,当数据插入或更新到表EMPLOYEES时,它负责检查表DEPARTMENTS中是否存在manager_id >

触发器可能是这样的:

create or update trigger manager_exists
before insert or update on employees 
for each row
begin
  if exists **new id** into Departments then
    INSERT DATA IN EMPLOYEES
  else
    "Error: MANAGER_ID doesnt exists in Departments"
  end if;
end manager_exists;

但我不知道如何创建这个触发器。 注意:我需要它作为触发器。帮助!

1 个答案:

答案 0 :(得分:1)

我是这样理解问题的:

create or replace trigger manager_exists
  before insert or update on employees
  for each row
declare
  l_mgr number;
begin
  select 1
    into l_mgr
    from dual
    where exists (select null 
                  from departments d
                  where d.manager_id = :new.manager_id
                 );
exception
  when no_data_found then
    raise_application_error(-20000, 'That manager does not exist in DEPARTMENTS');
end manager_exists;  
  

换句话说:

  • 检查您尝试插入到 MANAGER_ID 表中的 EMPLOYEES 是否存在于 DEPARTMENTS 表中
    • 不过,这对我来说没有多大意义;我会说你应该检查它反之亦然 - 检查 MANAGER_ID 你试图插入到 DEPARTMENTS 中是否存在 EMPLOYEES 表......但这不是你写的(或我误解了你的意思)
  • 如果是这样,很好,不要做任何事情(在触发器中);导致触发器触发的 insertupdate 语句将完成这项工作
  • 如果不是,则引发错误
相关问题