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