SQL Server外键中的DELETE CASCADE和UPDATE CASCADE

In this article, we will review on DELETE CASCADE AND UPDATE CASCADE rules in SQL Server foreign key with different examples.

在本文中,我们将使用不同的示例回顾SQL Server外键中的DELETE CASCADE和UPDATE CASCADE规则。

DELETE CASCADE: When we create a foreign key using this option, it deletes the referencing rows in the child table when the referenced row is deleted in the parent table which has a primary key.

DELETE CASCADE :当我们使用此选项创建外键时,当在具有主键的父表中删除引用行时,它将删除子表中的引用行。

UPDATE CASCADE: When we create a foreign key using UPDATE CASCADE the referencing rows are updated in the child table when the referenced row is updated in the parent table which has a primary key.

UPDATE CASCADE:当我们使用UPDATE CASCADE创建外键时,在具有主键的父表中更新引用行时,在子表中更新引用行。

We will be discussing the following topics in this article:

我们将在本文中讨论以下主题:

  1. Creating DELETE and UPDATE CASCADE rule in a foreign key using SQL Server management studio

    使用SQL Server Management Studio在外键中创建DELETE和UPDATE CASCADE规则
  2. Creating DELETE CASCADE and UPDATE CASCADE rule in a foreign key using T-SQL script

    使用T-SQL脚本在外键中创建DELETE CASCADE和UPDATE CASCADE规则
  3. Triggers on a table with DELETE or UPDATE cascading foreign key

    使用DELETE或UPDATE级联外键在表上触发

Let us see how to create a foreign key with DELETE and UPDATE CASCADE rules along with few examples.

让我们看看如何使用DELETE和UPDATE CASCADE规则创建外键以及一些示例。

使用DELETE和UPDATE CASCADE规则创建外键 (Creating a foreign key with DELETE and UPDATE CASCADE rules)

Using the SQL Server Management Studio GUI:

使用SQL Server Management Studio GUI:

Login to the SQL Server using SQL Server Management Studio, Navigate to the Keys folder in the child table. Right click on the Keys folder and select New Foreign Key.

使用SQL Server Management Studio登录到SQL Server,导航到子表中的Keys文件夹。 右键单击“ 密钥”文件夹,然后选择“ 新建外键”

Edit table and columns specification by clicking … as shown in the below image.

通过单击…编辑表和列的规格 ,如下图所示。

DELETE CASCADE foreign key in SQL Server

Select the parent table and the primary key column in the parent table. select the foreign key column in the child table. Click on OK. Please refer to the below sample image.

选择父表和父表中的主键列。 在子表中选择外键列。 单击确定。 请参考下面的示例图片。

Primary and Foreign key column mapping

In the INSERT and UPDATE specifications, select Cascade for the delete rule.

在INSERT和UPDATE规范中,选择Cascade作为删除规则。

cascade as delete rule on a foreign key in SQL Server

Click on Close and save the table in the designer. Click Yes in the warning message window.

单击关闭,然后将表保存在设计器中。 在警告消息窗口中单击“ ”。

warning window

Once you click on Yes, a foreign key with delete rule is created. Similarly, we can create a foreign key with UPDATE CASCADE rule by selecting CASCADE as an action for the update rule in INSERT and UPDATE specifications.

单击“ 是”后,将创建带有删除规则的外键。 类似地,我们可以通过选择CASCADE作为INSERT和UPDATE规范中的更新规则的动作来使用UPDATE CASCADE规则创建外键。

Foreign key in SQL Server

Using T-SQL:

使用T-SQL:

Please refer to the below T-SQL script which creates a parent, child table and a foreign key on the child table with DELETE CASCADE rule.

请参考下面的T-SQL脚本,该脚本使用DELETE CASCADE规则在子表上创建父表,子表和外键。

CREATE TABLE Countries
 
(CountryID INT PRIMARY KEY,
CountryName VARCHAR(50),
CountryCode VARCHAR(3))
 
 
CREATE TABLE States
 
(StateID INT PRIMARY KEY,
StateName VARCHAR(50),
StateCode VARCHAR(3),
CountryID INT)
 
 
 
ALTER TABLE [dbo].[States]  WITH CHECK ADD  CONSTRAINT [FK_States_Countries] FOREIGN KEY([CountryID])
REFERENCES [dbo].[Countries] ([CountryID])
ON DELETE CASCADE
GO
 
ALTER TABLE [dbo].[States] CHECK CONSTRAINT [FK_States_Countries]
GO

Insert some sample data using below T-SQL script.

使用下面的T-SQL脚本插入一些示例数据。

INSERT INTO Countries VALUES (1,'United States','USA')
 
INSERT INTO Countries VALUES (2,'United Kingdom','UK')
 
INSERT INTO States VALUES (1,'Texas','TX',1)
INSERT INTO States VALUES (2,'Arizona','AZ',1)

Sample data

Now I deleted a row in the parent table with CountryID =1 which also deletes the rows in the child table which has CountryID =1.

现在,我删除了具有CountryID = 1的父表中的行,这也删除了具有CountryID = 1的子表中的行。

deleting row in parent table

Please refer to the below T-SQL script to create a foreign key with UPDATE CASCADE rule.

请参考下面的T-SQL脚本,以使用UPDATE CASCADE规则创建外键。

CREATE TABLE Countries
 
(CountryID INT PRIMARY KEY,
CountryName VARCHAR(50),
CountryCode VARCHAR(3))
 
 
CREATE TABLE States
 
(StateID INT PRIMARY KEY,
StateName VARCHAR(50),
StateCode VARCHAR(3),
CountryID INT)
 
GO
 
INSERT INTO Countries VALUES (1,'United States','USA')
 
INSERT INTO Countries VALUES (2,'United Kingdom','UK')
 
INSERT INTO States VALUES (1,'Texas','TX',1)
INSERT INTO States VALUES (2,'Arizona','AZ',1)
 
GO
 
 
ALTER TABLE [dbo].[States]  WITH CHECK ADD  CONSTRAINT [FK_States_Countries] FOREIGN KEY([CountryID])
REFERENCES [dbo].[Countries] ([CountryID])
ON UPDATE CASCADE
GO
 
ALTER TABLE [dbo].[States] CHECK CONSTRAINT [FK_States_Countries]
GO

Now update CountryID in the Countries for a row which also updates the referencing rows in the child table States.

现在,将“国家/地区”中的CountryID更新为一行,这还将更新子表“状态”中的引用行。

UPDATE Countries SET CountryID =3 where CountryID=1

update cascade rule in SQL Server foreign key

Following is the T-SQL script which creates a foreign key with cascade as UPDATE and DELETE rules.

以下是T-SQL脚本,该脚本创建带有级联的外键作为UPDATE和DELETE规则。

ALTER TABLE [dbo].[States]  WITH CHECK ADD  CONSTRAINT [FK_States_Countries] FOREIGN KEY([CountryID])
REFERENCES [dbo].[Countries] ([CountryID])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
 
ALTER TABLE [dbo].[States] CHECK CONSTRAINT [FK_States_Countries]
GO

To know the update and delete actions in the foreign key, query sys.foreign_keys view. Replace the constraint name in the script.

要了解外键中的更新和删除操作,请查询sys.foreign_keys视图。 在脚本中替换约束名称。

SELECT name,delete_referential_action,delete_referential_action_desc,update_referential_action,update_referential_action_desc FROM sys.foreign_keys where name ='FK_States_Countries'

The below image shows that a DELETE CASCADE action and no UPDATE action is defined on the foreign key.

下图显示在外键上定义了DELETE CASCADE操作,而未定义UPDATE操作。

delete and update rules in SQL Server foreign key

Let’s move forward and check the behavior of delete and update rules the foreign keys on a child table which acts as parent table to another child table. The below example demonstrates this scenario.

让我们继续前进,检查删除和更新规则的行为,该行为将作为另一个子表的父表的子表上的外键。 下面的示例演示了这种情况。

In this case, “Countries” is the parent table of the “States” table and the “States” table is the parent table of Cities table.

在这种情况下,“ 国家 ”是“ 国家 ”表和“ ”表的父表是城市表的父表。

We will create a foreign key now with cascade as delete rule on States table which references to CountryID in parent table Countries.

现在,我们将在父表“国家/地区”中引用CountryID的“国家/地区”表上使用级联作为删除规则来创建外键。

CREATE TABLE Countries
 
(CountryID INT PRIMARY KEY,
CountryName VARCHAR(50),
CountryCode VARCHAR(3))
 
 
CREATE TABLE States
 
(StateID INT PRIMARY KEY,
StateName VARCHAR(50),
StateCode VARCHAR(3),
CountryID INT)
 
GO
 
 
CREATE TABLE Cities
(CityID INT,
CityName varchar(50),
StateID INT)
GO
 
INSERT INTO Countries VALUES (1,'United States','USA')
 
INSERT INTO Countries VALUES (2,'United Kingdom','UK')
 
INSERT INTO States VALUES (1,'Texas','TX',1)
INSERT INTO States VALUES (2,'Arizona','AZ',1)
 
INSERT INTO Cities VALUES(1,'Texas City',1)
INSERT INTO Cities values (1,'Phoenix',2)
 
GO
 
 
ALTER TABLE [dbo].[States]  WITH CHECK ADD  CONSTRAINT [FK_States_Countries] FOREIGN KEY([CountryID])
REFERENCES [dbo].[Countries] ([CountryID])
ON DELETE CASCADE
GO

Now on the Cities table, create a foreign key without a DELETE CASCADE rule.

现在,在“ 城市”表上,创建没有DELETE CASCADE规则的外键。

ALTER TABLE [dbo].[Cities]  WITH CHECK ADD  CONSTRAINT [FK_Cities_States] FOREIGN KEY([StateID])
REFERENCES [dbo].[States] ([StateID])
GO

If we try to delete a record with CountryID =1, it will throw an error as delete on parent table “Countries” tries to delete the referencing rows in the child table States. But on Cities table, we have a foreign key constraint with no action for delete and the referenced value still exists in the table.

如果我们尝试删除CountryID = 1的记录,则在父表“ countries ”上的delete尝试删除子表States的引用行时,它将引发错误。 但是在“ 城市”表上,我们有一个外键约束,没有任何删除操作,并且引用值仍然存在于表中。

DELETE FROM Countries where CountryID =1

The delete fails at the second foreign key.

删除在第二个外键上失败。

multiple childs

When we create the second foreign key with cascade as delete rule then the above delete command runs successfully by deleting records in the child table “States” which in turn deletes records in the second child table “Cities”.

当我们使用级联作为删除规则创建第二个外键时,上述删除命令将通过删除子表“ States ”中的记录而成功运行,这又会删除第二个子表“ Cities ”中的记录。

CREATE TABLE Countries
 
(CountryID INT PRIMARY KEY,
CountryName VARCHAR(50),
CountryCode VARCHAR(3))
 
 
CREATE TABLE States
 
(StateID INT PRIMARY KEY,
StateName VARCHAR(50),
StateCode VARCHAR(3),
CountryID INT)
 
GO
 
 
CREATE TABLE Cities
(CityID INT,
CityName varchar(50),
StateID INT)
GO
 
INSERT INTO Countries VALUES (1,'United States','USA')
 
INSERT INTO Countries VALUES (2,'United Kingdom','UK')
 
INSERT INTO States VALUES (1,'Texas','TX',1)
INSERT INTO States VALUES (2,'Arizona','AZ',1)
 
INSERT INTO Cities VALUES(1,'Texas City',1)
INSERT INTO Cities values (1,'Phoenix',2)
 
GO
 
 
ALTER TABLE [dbo].[States]  WITH CHECK ADD  CONSTRAINT [FK_States_Countries] FOREIGN KEY([CountryID])
REFERENCES [dbo].[Countries] ([CountryID])
ON DELETE CASCADE
GO
 
 
ALTER TABLE [dbo].[Cities]  WITH CHECK ADD  CONSTRAINT [FK_Cities_States] FOREIGN KEY([StateID])
REFERENCES [dbo].[States] ([StateID])
ON DELETE CASCADE
GO
 
DELETE FROM Countries where CountryID =1

使用删除级联或更新级联外键在表上触发 (Triggers on a table with delete cascade or update cascade foreign key)

An instead of an update trigger cannot be created on the table if a foreign key on with UPDATE CASCADE already exists on the table. It throws an error “Cannot create INSTEAD OF DELETE or INSTEAD OF UPDATE TRIGGER ‘trigger name’ on table ‘table name’. This is because the table has a FOREIGN KEY with cascading DELETE or UPDATE.”

如果表上已经存在带有UPDATE CASCADE的外键,则不能在表上创建替代更新触发器。 它将引发错误“无法在表'表名'上创建INSTEAD OF DELETE或INSTEAD OF UPDATE触发器'触发名'。 这是因为该表具有带有级联DELETE或UPDATE的FOREIGN KEY。”

INSTEAD OF TRIGGERS on table with foreign key

Similarly, we cannot create INSTEAD OF DELETE trigger on the table when a foreign key CASCADE DELETE rule already exists on the table.

同样,当表上已经存在外键CASCADE DELETE规则时,我们无法在表上创建INSTEAD OF DELETE触发器。

结论 (Conclusion)

In this article, we explored a few examples on DELETE CASCADE and UPDATE CASCADE rules in SQL Server foreign key. In case you have any questions, please feel free to ask in the comment section below.

在本文中,我们探索了一些有关SQL Server外键中的DELETE CASCADE和UPDATE CASCADE规则的示例。 如果您有任何疑问,请随时在下面的评论部分中提问。

Please refer to this article, SQL Server foreign key to dig in more details on delete and update rules in SQL Server foreign key.

请参阅本文SQL Server外键,以深入了解SQL Server外键中的删除和更新规则。

翻译自: https://www.sqlshack.com/delete-cascade-and-update-cascade-in-sql-server-foreign-key/

  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值