触发工资时如何获得雇员的名字?

时间:2019-03-14 02:57:20

标签: oracle plsql database-trigger

create or replace trigger trg_t3 after  
    insert OR update or delete of salary  on t2 
    for each row  
begin 
   if 
    to_char(systimestamp,'hh24') not between 9 and 17 
   then 
    insert into  t3  values (:new.salary, :old.salary, sysdate);
   else
     DBMS_OUTPUT.put_line ('update is not possible  between 9:00 and 17:00');
   end if;        
end; 
/

这将根据表t3的触发器中提到的条件在表t2上插入旧工资,新工资和时间。但是我需要更新或删除薪水的雇员的姓名。

如果我要更新t2的薪水,则需要在t3中插入其薪水已被修改的特定员工的姓名。但是当前方法只会插入旧薪水,新薪水和时间

这是用于创建表的代码

create table t2 ( name varchar(20), salary varchar2(20));
create table t3 (salary_new   varchar2(50), salary_old  varchar2(20), log_date date);

insert all 
into t2 values('hari',2000) 
into t2 values('sam',40000)
into t2 values('ravi',60000)
into t2 values('manoj',8000)
into t2 values('pratheep',10000)
into t2 values('john',3000)
into t2 values('joe',50000)
into t2 values('scott',70000)
select * from dual;

3 个答案:

答案 0 :(得分:2)

您的触发器被标记为after insert or update or delete。您必须处理所有三种情况,否则它将无法正常工作,因为插入时我们没有:old值,而删除时我们没有:new

因此,如果您使用:new.name,则delete将放置空值。如果您使用:old.name,则insert将无法正常工作。使用变量或按如下所示操作:

create or replace trigger trg_t3 after
  insert or update or delete of salary on t2 for each row
begin
  if to_char(systimestamp,'hh24') between 9 and 17 then
    dbms_output.put_line ('update is not possible between 9:00 and 17:00');
  else
    if deleting then
      insert into t3 (salary_new, salary_old, name, log_date)
        values (null, :old.salary, :old.name, sysdate);
    elsif inserting then
      insert into t3 (salary_new, salary_old, name, log_date)
        values (:new.salary, null, :new.name, sysdate);
    elsif updating then
      insert into t3 (salary_new, salary_old, name, log_date)
        values (:new.salary, :old.salary, :new.name, sysdate);
    end if;
  end if;
end;

答案 1 :(得分:1)

执行插入选择

insert into  t3  
select emp.name, :new.salary, :old.salary, sysdate
from emp where emp.id = :old.id;

答案 2 :(得分:1)

首先,您需要一个字段以将名称插入其中,因此将t3创建为

create table t3 (salary_new   varchar2(50), salary_old  varchar2(20), log_date date, name varchar(20));

然后只需在触发器中使用

insert into  t3  values (:new.salary, :old.salary, sysdate, :new.name);

您可以使用:new.name或:old.name,因为它不会更改,因此将是相同的值。