First I create a table with this script :
CREATE TABLE [dbo].[Employee_Demo] (
[Emp_ID] [bigint] IDENTITY (1, 1) NOT NULL ,
[Emp_Name] [varchar] (55) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Emp_Sal] [decimal](10, 2) NULL
) ON [PRIMARY]
and then I create another table
CREATE TABLE [dbo].[Employee_Demo_Audit] (
[Emp_ID] [int] NULL ,
[Emp_Name] [varchar] (55) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Emp_Sal] [decimal](10, 2) NULL ,
[Audit_Action] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Audit_Timestamp] [datetime] NULL
) ON [PRIMARY]
after that I create an INSTEAD OF UPDATE
trigger on table employee_demo
:
CREATE TRIGGER trgInsteadOfUpdate ON dbo.Employee_Demo
INSTEAD OF Update
AS
declare @emp_id int, @emp_name varchar(55), @emp_sal decimal(10,2), @audit_action varchar(100);
select @emp_id=i.Emp_ID from inserted i;
select @emp_name=i.Emp_Name from inserted i;
select @emp_sal=i.Emp_Sal from inserted i;
IF UPDATE (Emp_sal)
begin
BEGIN
BEGIN TRAN
if(@emp_sal>=1000)
begin
RAISERROR('Cannot Insert where salary fewer then 1000',16,1); ROLLBACK; end
else begin
insert into Employee_Demo_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp) values(@emp_id,@emp_name,@emp_sal,@audit_action,getdate());
COMMIT;
PRINT 'Record Updated -- Instead Of Update Trigger.'; END; end
end
I don't know why if I update table employee_demo
with this script :
UPDATE employee_demo
SET emp_name = 'ZHEE'
WHERE emp_id = 1
the name of emp_id = 1
is doesn't change...
Why ????
这可能与以下事实有关:您在源表中使用bigint作为id,而在审计表中仅使用常规int?
The instead of
trigger replaces the default behavior. Your trigger appears to perform an update only if the Emp_sal
column is being changed. If that column is not being updated, no update statement is executed.
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.