2012-12-31 46 views
0

我有一個項目來實現插入,更新和從Northwind -> Customers刪除Customers的表格。我設法在每次操作後都進行插入,更新和刷新,但刪除不起作用並拋出FK異常。我需要級聯刪除上,但我不知道如何..級聯刪除客戶的存儲過程?

我的形式如下:

enter image description here

和我進行刪除(到目前爲止,還沒有級聯)過程:

CREATE Procedure [dbo].[DeleteCustomer] 
(
    @Original_CustomerID nchar(5) 
) 
AS 
    SET NOCOUNT OFF; 

    DELETE FROM [dbo].[Customers] 
    WHERE 
    (
    (
     [CustomerID] = @Original_CustomerID 
    ) 
) 

在某些情況下工作,但在別人我得到一個錯誤:

DELETE語句與REFERENCE約束「FK_Orders_Customers」衝突。衝突發生在數據庫「Northwind」, 表「dbo.Orders」,列'CustomerID'中。該聲明已被終止 。

任何人都可以幫我完成這個項目通過添加級聯刪除?

這是Northwind Traders數據庫,Customer表。

+0

從'dbo.Orders'第一刪除由'CustomerId'然後刪除'dbo.Customers' –

+0

我: ' DELETE FROM [DBO] [訂單] WHERE ( \t( \t [客戶] = @Original_CustomerID \t) ) DELETE FROM [DBO]。[客戶] WHERE ( \t( \t \t [客戶] = @Original_CustomerID \t) ) ' ,但仍是同樣的錯誤。我如何添加級聯?你可以請代碼這個程序..? – Fengson

回答

0

一個簡單的方法來處理,這是下降,並重新進行添加約束的級聯在SQL企業管理器中刪除約束(或您所選擇的ISQLW翻譯):如果你想有一個嚴格的

USE Northwind 
GO 
ALTER TABLE Orders 
    DROP CONSTRAINT 
    FK_Orders_Customers 
GO 
ALTER TABLE Orders 
    ADD 
    CONSTRAINT FK_Orders_Customers FOREIGN KEY 
    (
     CustomerID 
    ) REFERENCES Customers 
     CustomerID 
    ) ON CASCADE DELETE 
GO 

存儲過程解決方案,您可以使用您的原始存儲過程的此修訂版本:

CREATE Procedure [dbo].[DeleteCustomer] (
    @Original_CustomerID nchar(5) 
) 
AS 

SET NOCOUNT OFF; 

    DELETE 
    FROM [dbo].[Orders] 
    WHERE [CustomerID] = @Original_CustomerID 

    DELETE 
    FROM [dbo].[Customers] 
    WHERE [CustomerID] = @Original_CustomerID 
+0

我在哪裏運行此代碼?我是否將其保存爲存儲過程或? – Fengson

+0

您將使用您用於創建存儲過程的相同工具。 –

+0

偉大的,最後一件事。如何以及在何處保存您在準備最終項目時發佈的代碼?將它作爲查詢或存儲過程保存在我的StoredProcedures文件夾中? – Fengson

0

我在哪裏放置您的代碼?作爲存儲過程保存/運行嗎? 它仍然拋出該異常..:/ 我刪除:

private void buttonDelete_Click(object sender, RoutedEventArgs e) 
{    
    SqlConnection cn = new SqlConnection(@"Integrated Security=SSPI;Initial Catalog=Northwind;Data Source=(local)"); 
    SqlCommand cmd = new SqlCommand("DeleteCustomer", cn); 
    cmd.CommandType = CommandType.StoredProcedure; 

    cmd.Parameters.AddWithValue("@Original_CustomerID", textBox_CompanyID.Text); 

    cn.Open(); 
    cmd.ExecuteNonQuery(); 
    cn.Close(); 

    lbxCustomers.Items.Clear(); 
    this.init(); 
} 

DeleteCustomer程序:

CREATE Procedure [dbo].[DeleteCustomer] 
(
    @Original_CustomerID nchar(5) 
) 
AS 

SET NOCOUNT OFF; 

DELETE FROM [dbo].[Customers] 
WHERE 
(
    (
     [CustomerID] = @Original_CustomerID 
    ) 
) 

我有你的代碼,但不知道如何將它添加到我的項目使其工作。所以當我重新啓動應用程序或切換電腦時,它仍然可以工作請幫助..我認爲這是新的錯誤。有連接3個表,因爲它似乎:

The DELETE statement conflicted with the REFERENCE constraint "FK_Order_Details_Orders". The conflict occurred in database "Northwind", table "dbo.Order Details", column 'OrderID'. 
The statement has been terminated. 
+0

您需要將您的DeleteCustomer存儲過程更改爲提供的某個competent_tech(或類似的工具)。你這樣做的方式是發出DROP PROCEDURE命令,如DROP PROCEDURE dbo.DeleteCustomer,然後運行CREATE PROCEDURE命令。您可以通過突出顯示SQL Management Studio中的文本並按F5來做到這一點。只有您突出顯示的文本纔會運行。 – NYCdotNet