【问题标题】:How to get name of the employee while triggering his salary?如何在触发工资的同时获取员工的姓名?
【发布时间】:2019-03-14 02:57:19
【问题描述】:
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; 
/

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

如果我要更新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;

【问题讨论】:

    标签: oracle plsql database-trigger


    【解决方案1】:

    您的触发器被标记为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;
    

    【讨论】:

      【解决方案2】:

      插入选择

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

      【讨论】:

      • 如果我有一个 id 列,上述语句将起作用。但是如果我没有呢.. 我已经发布了表格的代码
      • 如果你的表没有某种ID列,你的数据库设计有更大的问题需要首先解决
      • Shaun 的回答在这种情况下更好;但请记住,这种技术可以很容易地用于从其他表中引入数据
      【解决方案3】:

      首先您需要一个字段来插入名称,因此将 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 ,因为它不会改变,所以是相同的值。

      【讨论】:

      • 是的,它有效..我不知道我们可以在名称上使用 :old:new 。谢谢肖恩
      猜你喜欢
      • 2017-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-12
      • 2022-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多