牛人请进,触发器问题
我想往一个表插入数据的时候,用触发器把这条记录同样插入到另一个表,该怎么写?如果是删除呢,怎样把要删除的数据用触发器转存至另一个表。还有我参照书上的写了个修改的例子,但是不往另一个表里写。也就是修改这条记录,同时把这条记录转存至另一个表。
CREATE TRIGGER [TEST] ON [dbo].[employees]
FOR INSERT,UPDATE
AS
BEGIN
INSERT INTO dbo.empbak ([id],username,password,phone,email)
SELECT INSERTED.[id], INSERTED.username,INSERTED.password,INSERTED.phone,INSERTED.email
FROM INSERTED WHERE id=1
UPDATE employees SET password='11111' FROM employees T,INSERTED I WHERE T.id=I.id and T.f1=20
END
下面是employees表的结构:
create table employees(
id] int IDENTITY (1, 1) NOT NULL primary key,
username varchar(45) COLLATE Chinese_PRC_CI_AS NOT NULL ,
password varchar (15) COLLATE Chinese_PRC_CI_AS NOT NULL ,
phone varchar(15) COLLATE Chinese_PRC_CI_AS NOT NULL ,
email varchar(60) COLLATE Chinese_PRC_CI_AS NOT NULL
)
请大侠牛人解答,先谢谢了。
------解决方案--------------------
SQL code
create trigger my_trig on tb1 for insert ,update ,delete
as
if not exists(select 1 from inserted)
insert into tb2 select * from deleted
else
insert into tb2 select * from inserted