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


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM