2013-09-27 40 views
0
之間服務器

比方說,我有2個表2級聯刪除在SQL中2個表

CREATE TABLE [dbo].[People](
    [ID] [int] IDENTITY(1,1) NOT NULL, 
    [Nom] [nvarchar](50) NOT NULL, 
CONSTRAINT [PK_People] PRIMARY KEY CLUSTERED 
(
    [ID] ASC 
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 
) ON [PRIMARY] 

CREATE TABLE [dbo].[Transactions](
    [ID] [int] IDENTITY(1,1) NOT NULL, 
    [BUYER_ID] [int] NOT NULL, 
    [SELLER_ID] [int] NOT NULL, 
    [DateTransaction] [datetime] NOT NULL, 
CONSTRAINT [PK_Transactions] PRIMARY KEY CLUSTERED 
(
    [ID] ASC 
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 
) ON [PRIMARY] 

的邏輯是,交易表,需要從人表2分的記錄,買家和一個賣家。

我想要做的是在BUYER_ID和SELLER_ID列上實現級聯刪除。

不過,我可以添加一個(或)順利,但如果我嘗試添加第二個,當我去救人,我得到一個錯誤信息......

Unable to create relationship 'FK_Transactions_Buyer'. 
Introducing FOREIGN KEY constraint 'FK_Transactions_Buyer' on table 'Transactions' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. 

是否有如何在不使用觸發器的情況下執行此操作,或者觸發器是執行此操作的最佳方法

回答

0

這就是我最終這樣做的結果,我嚴重懷疑這是最好的方法。

我修改了外鍵不強制外鍵約束。

ALTER TABLE [dbo].[Transactions] NOCHECK CONSTRAINT [FK_Transactions_Buyer] 

ALTER TABLE [dbo].[Transactions] NOCHECK CONSTRAINT [FK_Transactions_Seller] 

而且還修改了交易表添加請將isDeleted場

[IsDeleted] [bit] NULL 

最後,我添加了一個刪除觸發器向人民表裏面設置請將isDeleted爲True每當在人員表中刪除Buyer_ID或Seller_Id時的交易表

最後在觸發器結束時,我刪除了標記爲IsDeleted的事務中的所有記錄設置爲true。

CREATE TRIGGER [dbo].[deletePeople] 
    ON [dbo].[People] 
    AFTER DELETE 
AS 
BEGIN 
    -- SET NOCOUNT ON added to prevent extra result sets from 
    -- interfering with SELECT statements. 
    SET NOCOUNT ON; 


    DECLARE @DeletedId INT 
    SELECT @DeletedId = id FROM deleted 
    -- Insert statements for trigger here 
    Update dbo.Transactions SET IsDeleted = 1 WHERE BUYER_ID = @deletedId or SELLER_ID = @deletedId 
    DELETE FROM dbo.Transactions WHERE IsDeleted = 1 
END 

就像我說的,我懷疑這是一個正確的做法

1

引用事務的人員的FK約束可能會導致此問題。 如果不是這種情況,我認爲答案是將兩個鍵都包含在一個約束中。 如果買方和賣方ID都相同,並且該人員已被刪除,則這兩個約束可能會嘗試刪除同一行。 這是我能想到的SQL服務器可能會試圖避免的唯一場景...

道歉我不能更明確!

+0

我添加了約束需要不同的ID在同一交易買方和賣方。這並不能解決問題。 – SerenityNow