用触发器进行级联删除
原文:http://blog.csdn.net/lixueru0819/article/details/6841572
这次遇到的问题是表的级联删除,当删除一个主键信息时会出错,因为还有外键信息,要想全部删除就用到了触发器。
- <span style="font-family:Microsoft YaHei;font-size:16px;color:#6600cc;">CREATE TRIGGER trigCategoryDelete (创建触发器)
- ON Category (在哪个表上创建)
- after DELETE (引发触发器的事件)
- AS
- BEGIN
- delete news where caID=(select id from deleted)(触发器引发后的一些处理语句)
- END
- </span>
但是after是在delete发生之后的,所以这样还是会报错。删除操作都已经结束了还怎么删除外键呢。
instead of 代替删除语句:
- <span style="font-family:Microsoft YaHei;font-size:16px;color:#6600cc;">ALTER TRIGGER [dbo].[trigCategoryDelete]
- ON [dbo].[category]
- instead of DELETE
- AS
- BEGIN
- declare @id int
- select @id=id from deleted
- --删除新闻
- delete news where caId=@id
- --删除新闻类别
- delete category where id=@id
- END</span>
这样就能删除外键里的信息了。
如果是三个表的级联删除
- <span style="font-family:Microsoft YaHei;font-size:16px;color:#6600cc;">ALTER TRIGGER [dbo].[trigCategoryDelete]
- ON [dbo].[category]
- instead of DELETE
- AS
- BEGIN
- declare @caId int
- select @caId=id from deleted
- --删除评论
- delete comment where newsId = (select id from news where caId=@caId)
- --删除新闻
- delete news where caId=@caId
- --删除新闻类别
- delete category where id=@caId
- END</span>
但是这样的话会报错,错就错在一条新闻下对应着多条评论,解决办法就是把“=”改为“in”,这样所有查处的评论都可以删除了
ps:至于前面出发器的名称和表的名称不太一样,相信大部分人都知道,当保存触发器后,再打开的时候就会自动补全表信息。