sql 触发器 针对一张表数据写入 另一张表 的增删改

时间:2022-10-02 00:43:33

ALTER TRIGGER [dbo].[tri_test2]
ON [dbo].[student]
for INSERT,DELETE,UPDATE
AS
BEGIN

if not exists (select * from deleted) --新增
insert student2(stu_id,stu_name,stu_sex,stu_birthday,class_id)
select stu_id,stu_name,stu_sex,stu_birthday,class_id from inserted
else if not exists(select * from inserted) --删除
delete student2 from deleted d where student2.stu_id=d.stu_id
else if (select count(*) from deleted)>0 and (select count(*) from inserted)>0 --更新
update student2 set stu_name=i.stu_name ,stu_sex=i.stu_sex from student2 b, inserted i,deleted d
where i.stu_id=d.stu_id and i.stu_id=d.stu_id

END

--------------------------------- 添加时修改另一表数据

ALTER TRIGGER [dbo].[stu_insert]
ON [dbo].[student]
for insert
AS
BEGIN

update class set class_num=class_num+1
where class_id=(select class_id from inserted)

END