如何刪除有主外鍵關系的數據呢?


舉個例子,比如一個新聞發布系統,有類別表,新聞表和評論表,分別設立主外鍵關系。

如圖:

 

 

 那如何刪除類別表中的國際新聞是,連同其下的新聞表和評論表也一同刪除呢?

兩種方法,第一種很簡單,當在創建主外鍵時,如圖所示:

 把刪除規則設為層疊(SQL2005),在SQL2008中又叫做級聯了!

類別表和新聞表,新聞表和評論表都要設為層疊。

第二種就是寫觸發器了!

這是類別表的觸發器:

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

-- =============================================
--
Author: <zxj>
--
Create date: <2012>
--
Description: <刪除類觸發器>
--
=============================================
ALTER TRIGGER [trigCategoryDelete]
ON [dbo].[cateGory]
instead of DELETE
AS
BEGIN
--select * from deleted
declare @caid int
select @caid=id from deleted
--delete news where caId=(select id from deleted)


--select * from comment where newsid in(select id from news where caid=@caid)
--
刪除評論
delete comment where newsID in (select Id from news where caid=@caid)
--刪除新聞
delete news where caId=@caid
--刪除類別
delete category where id=@caid
END

 

 

 


免責聲明!

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



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