为什么命令级联删除在我的代码中不起作用

时间:2018-09-07 15:11:07

标签: sql-server

你好,当我从CustomerOrder删除记录仍保留在Customer中时,有人可以检查为什么级联删除选项不起作用吗?

Create database demodb 
GO
Use demodb 
GO



Create table dbo.Customer
(
CustomerID int identity(1,1) primary key,
CustomerName nvarchar(30) not null
);
GO



Insert into dbo.Customer
Values ('Mario Saric'), ('Maja Majic');


Create Table dbo.CustomerOrder(
CustomerOrderID int identity(1001,1) primary key,
CustomerID int not null,
OrderAmount decimal(4,2));
GO

Select * from dbo.Customer


insert into dbo.CustomerOrder
values(1, 44.22), (2, 33.33);



insert into dbo.CustomerOrder
values(5, 42.22);


Delete from Customer
Where CustomerID=1;



Alter Table dbo.CustomerOrder
Drop Constraint FK__CustomerO__Custo__164452B1;
GO

Alter Table dbo.CustomerOrder
Add Constraint FK_CustomerOrder_Customer 
foreign Key (CustomerID)
References dbo.Customer (CustomerID)
On delete cascade;
GO

Select * From CustomerOrder;


Delete from dbo.CustomerOrder
where CustomerID = 2;

Select * From dbo.CustomerOrder;

Select * From dbo.Customer

1 个答案:

答案 0 :(得分:1)

请尝试从Customer表中删除,而不是从CustomerOrder表中删除。

客户订单实际上是子表。例如,您可能有一个取消订单的客户,在这种情况下,您只想从CustomerOrder表中删除该订单。

如果要删除客户,则还希望删除其所有订单。这就是级联删除的目的。从客户中删除还会删除其客户订单。