0

我有一个项目来实现一个CustomersNorthwind -> Customers. 我设法在每次操作后进行插入、更新和刷新,但删除不起作用并引发 FK 异常。我需要级联删除,但我不知道如何..

我的表格如下所示:

在此处输入图像描述

和我的删除程序(到目前为止,没有级联):

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表格。

4

2 回答 2

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
于 2012-12-31T02:06:00.197 回答
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.
于 2012-12-31T03:05:51.100 回答