sql 觸發器 針對一張表數據寫入 另外一張表 的增刪改

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

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_idtest

ENDdate

--------------------------------- 添加時修改另外一表數據select

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)數據

ENDdb

相關文章
相關標籤/搜索