我们如何创建一个触发器,在该触发器中,工资变化或总工资变化。 [英] How we can create a trigger in which changes on emp salary or pf his total salary change.
问题描述
创建表员工(
emp_id int,
emp_name varchar(50),
emp_base money,
emp_Pf money,
emp_DA money,
emp_total money
)
当我们改变基数时,pf,da total将通过触发器自动改变。
如果我理解正确的问题你需要添加base,pf和da来计算总数,以防任何改变。
如果是这种情况那么触发器就可以了看起来像
创建 TRIGGER employee_trigger
ON employee
AFTER INSERT ,更新 AS
BEGIN
更新 e
SET e.emp_total = COALESCE (e.emp_base, 0 )
+ COALESCE (e.emp_Pf, 0 )
+ COALESCE (e.emp_DA, 0 )
FROM 员工e INNER JOIN 已插入i
ON e.emp_id = i.emp_id;
END ;
有两件事需要注意,首先我使用过连接单个SQL语句可能会更改表中的多个行,在这种情况下,此触发器只会运行一次。在那种情况下,插入的表将为每行更改包含一行。
另一件事是使用COALESCE。根据您的表定义,三列中的任何一列都可能为NULL,因此在这种情况下我将NULL替换为零。
但是,我不会以这种方式解决问题。更简单的方法是使用计算列。这也会带来更好的性能。
因此,如果根据这些列计算总数,我只需将表格定义如下
CREATE TABLE employee(
emp_id int ,
emp_name varchar ( 50 ),
emp_base money ,
emp_Pf money ,
emp_DA money ,
emp_total AS COALESCE (emp_base , 0 )
+ COALESCE (emp_Pf, 0 )
+ COALESCE (emp_DA, 0 )
) ;
create table employee(
emp_id int,
emp_name varchar(50),
emp_base money,
emp_Pf money,
emp_DA money,
emp_total money
)
when we change on base ,pf,da total will change by trigger automatic.
If I understand the question correctly you need to add base, pf, and da to calculate total in case any of those change.
If this is the case then the trigger could look something like
CREATE TRIGGER employee_trigger ON employee AFTER INSERT, UPDATE AS BEGIN UPDATE e SET e.emp_total = COALESCE(e.emp_base, 0) + COALESCE(e.emp_Pf, 0) + COALESCE(e.emp_DA, 0) FROM employee e INNER JOIN inserted i ON e.emp_id = i.emp_id; END;
There are two things to notice, first I've used a join since a single SQL statement may change several rows in a table and in such case this trigger would be run only once. In that situation the inserted table would contain one row for each row changed.
The other thing is the use of COALESCE. Based on your table definition, any of the three columns may be NULL so in such case I replaced the NULL with zero.
However, I wouldn't actually solve the problem this way. Much easier way would be to use computed columns. This would also yield to much better performance.
So if the total is calculated based on those columns I would simply define the table as follows
CREATE TABLE employee( emp_id int, emp_name varchar(50), emp_base money, emp_Pf money, emp_DA money, emp_total AS COALESCE(emp_base, 0) + COALESCE(emp_Pf, 0) + COALESCE(emp_DA, 0) );
这篇关于我们如何创建一个触发器,在该触发器中,工资变化或总工资变化。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!