- CREATE TRIGGER triggerName ON table
- AFTER INSERT |After Delete |After Upadte
- AS BEGIN
- INSERT INTO dbo.UserHistory............
- END
Example
1. Create a Table:
- CREATE TABLE Employee_Test
- (
- Emp_ID INT Identity,
- Emp_name Varchar(100),
- Emp_Sal Decimal (10,2)
- )
- INSERT INTO Employee_Test VALUES ('Anees',1000);
- INSERT INTO Employee_Test VALUES ('Rick',1200);
- INSERT INTO Employee_Test VALUES ('John',1100);
- INSERT INTO Employee_Test VALUES ('Stephen',1300);
- INSERT INTO Employee_Test VALUES ('Maria',1400);
- CREATE TABLE Employee_Test_Audit
- (
- Emp_ID int,
- Emp_name varchar(100),
- Emp_Sal decimal (10,2),
- Audit_Action varchar(100),
- Audit_Timestamp datetime
- )
create trigger AFTER_INSERT_DELETE
on [dbo].[employee_test]
after insert ,delete
as
begin
declare @audit_action varchar(50);
set @audit_action='Inserted iteam';
insert into [dbo].[employee_test_audit]
(emp_id,emp_name,emp_sal,audit_action,audit_timestamp)
select i.emp_id,i.emp_name,i.emp_sal,@audit_action,getdate() from inserted i;
set @audit_action='Deleted iteam';
insert into [dbo].[employee_test_audit]
select d.emp_id,d.emp_name,d.emp_sal,@audit_action,getdate() from deleted d;
end
AFTER UPDATE
alter trigger update_salary on [dbo].[employee_test]
after update ,insert,delete
as
begin
declare @empname varchar(25), @newsalary int,@audit_action varchar(40);
select @empname=i.emp_name from inserted i;
select @newsalary=i.emp_sal from inserted i;
if update(emp_name)
begin
set @audit_action='N_update';
end
if update(emp_sal)
begin
set @audit_action='S_update';
end
insert into [dbo].[employee_test_audit] (emp_id,emp_name,emp_sal,audit_action,audit_timestamp)
select i.emp_id,@empname,@newsalary,@audit_action,getdate() from inserted i;
end
No comments:
Post a Comment