Click here to Skip to main content
15,881,172 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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.
Posted
Comments
Wendelius 28-Sep-15 0:16am    
Two questions
- how would the salary and pf totals be calculated?
- is this Oracle or SQL Server (you have tagged both)
Khushi Saraswat 28-Sep-15 0:42am    
It's sql
Wendelius 28-Sep-15 0:45am    
Okay, and what is the formula for the totals? How they are to be calculated?
Khushi Saraswat 28-Sep-15 0:53am    
I need to insert total of base salary,pf and da in total salary column on change of any one of base,pf and da
Khushi Saraswat 28-Sep-15 23:07pm    
Thanks i want to ask one thing how pivot work in sql can u explain please

1 solution

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
SQL
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
SQL
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)
);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900