create trigger AfterA on A for
insert,update,delete
as
declare @id int;
begin
if exists(select 1 from inserted) and not exists (select 1 from deleted)
begin
insert into b select inserted.id,'1',getdate() from inserted
end
if exists(select 1 from inserted) and exists (select 1 from deleted)
begin
insert into b select inserted.id,'3',getdate() from inserted,deleted where inserted.id = deleted.id
end
if not exists(select 1 from inserted) and exists (select 1 from deleted)
begin
insert into b select deleted.id,'2',getdate() from deleted;
end
end
----1、2、3分别对应了增删改操作
SQLServer 简单的触发器的例子 - inserted 与 deleted的使用
这个例子,就是
A是主表
B是 日志表, 负责记录 A表 发生的变化。
的一个例子
和你的有点相像, 又有点差异.
你可以看看, 参考一下.
给你个参考
//insert触发器
Create TRIGGER [dbo].[T_aa_insert] ON [dbo].[aa]
FOR INSERT
AS
DECLARE
@a1 varchar(20),
@a2 varchar(20),
@a3 varchar(20)
SELECT
@a1 = a1,
@a2 = a2,
@a3 = a3
FROM Inserted
insert into bb values(@a1,@a2,@a3);
//Delete触发器
Create TRIGGER [dbo].[T_aa_delete] ON [dbo].[aa]
FOR DELETE
AS
DECLARE
@a1 varchar(20),
@a2 varchar(20),
@a3 varchar(20)
SELECT
@a1 = a1,
@a2 = a2,
@a3 = a3
FROM deleted
delete from bb
where b1=@a1 and b2=@a2 and b3=@a3
//update触发器
Create TRIGGER [dbo].[T_aa_update] ON [dbo].[aa]
FOR UPDATE
AS
DECLARE
@INSa1 varchar(20),
@INSa2 varchar(20),
@INSa3 varchar(20)
SELECT
@INSa1 = a1,
@INSa2 = a2,
@INSa3 = a3
FROM inserted
DECLARE
@DELa1 varchar(20),
@DELa2 varchar(20),
@DELa3 varchar(20)
SELECT
@DELa1 = a1,
@DELa2 = a2,
@DELa3 = a3
FROM deleted
update bb set b1=@INSa1, b2=@INSa2, b3=@INSa3
where b1=@DELa1 and b2=@DELa2 and b3=@DELa3