I'm creating my first trigger in sql server 2008 . I have two tables, employee
and employee_audit
.
employee
table have three fields empno
( auto increment ), first_name
and last_name
employee_audit
table have empno
( auto increment ) last_name. I want to create trigger on employee
and update its last name and before update this last name I want to store employee
table's last_name
in employees_audit
table's last_name
create trigger before_employee_update
on employee
after update
as
declare @last_name varchar(20)
select @last_name = i. last_name from inserted i;
Begin
Insert into employees_audit(last_name)
values(@last_name);
end;
what I have to write instead of "after" cz I first want to store the old last_name value in employees_audit table and then want to update last_name value in employee
and before is not recognized trigger in sql server
Trigger to insert last name in employee_audit table Instead of updating the record in employee table.
Use Instead of update trigger to do this. below is the query please refer it:
Create trigger InsOf_update_employee on employee
Instead of update
as
declare @last_name varchar(20)
select @last_name = i. last_name from inserted i;
if update(last_name)
begin
insert into employees_audit (last_name) values (@last_name);
end
print 'Successfully fired the before update trigger'
Go
then try to update the employee table's last name field of any record. example:
update employee set last_name='xyz' where empno=2;
It will insert the record in employee_audit table during updating the employee table.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.