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.

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

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.

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

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

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

Click on Close and save the table in the designer. Click Yes in the warning message 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规则创建外键。

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
GOALTER 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)

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的子表中的行。

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)GOINSERT 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)GOALTER TABLE [dbo].[States]  WITH CHECK ADD  CONSTRAINT [FK_States_Countries] FOREIGN KEY([CountryID])
REFERENCES [dbo].[Countries] ([CountryID])
ON UPDATE CASCADE
GOALTER 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

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
GOALTER 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操作。

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)GOCREATE TABLE Cities
(CityID INT,
CityName varchar(50),
StateID INT)
GOINSERT 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)GOALTER 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.

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

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)GOCREATE TABLE Cities
(CityID INT,
CityName varchar(50),
StateID INT)
GOINSERT 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)GOALTER TABLE [dbo].[States]  WITH CHECK ADD  CONSTRAINT [FK_States_Countries] FOREIGN KEY([CountryID])
REFERENCES [dbo].[Countries] ([CountryID])
ON DELETE CASCADE
GOALTER TABLE [dbo].[Cities]  WITH CHECK ADD  CONSTRAINT [FK_Cities_States] FOREIGN KEY([StateID])
REFERENCES [dbo].[States] ([StateID])
ON DELETE CASCADE
GODELETE 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。”

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/

SQL Server外键中的DELETE CASCADE和UPDATE CASCADE相关推荐

  1. sql server 外键_什么是SQL Server中的外键

    sql server 外键 In this article, we will seek an answer to an important question – "What is a for ...

  2. SQL Server外键约束

    A. SQL Server外键约束 SQL Server外键约束简介 外键是一个表中的一列或一组列,它唯一地标识另一个表的行. vendor_groups 和v endor 表,它们的结构如下: 每个 ...

  3. MySQL外键约束On Delete、On Update各取值的含义

    主键.外键和索引的区别?   主键 外键 索引 定义: 唯一标识一条记录,不能有重复的,不允许为空 表的外键是另一表的主键, 外键可以有重复的, 可以是空值 主索引(由关键字PRIMARY定义的索引) ...

  4. mysql on delete关键字_MySQL外键约束On Delete、On Update各取值的含义

    主键.外键和索引的区别? 主键 外键 索引 定义: 唯一标识一条记录,不能有重复的,不允许为空 表的外键是另一表的主键,外键可以有重复的,可以是空值 主索引(由关键字PRIMARY定义的索引),用于表 ...

  5. SQL server 外键约束操作

    创建数据库时就是有主键的创建了主键,但是表之间的关系没有联系,要建数据库关系图只有主键没有外键时不行的. 建外键的前提是此外键必须是另外一个表的主键.建外键的步骤: 第一步.打开要建外键的表设计器,右 ...

  6. Sql Server 从日志中恢复误删除或误Update的数据

    最近在研究SQL Server日志,基本明白日志的记录方式. 如果数据库在创建时 "恢复模式"是"完整"模式,那么,在对数据库做的任何操作都会记录在LDF日志文 ...

  7. sql server 快照_在SQL Server合并复制中应用快照时出现外键问题

    sql server 快照 This article will review specific SQL Server merge replication issues related to forei ...

  8. mysql外键约束cascade_mysql外键约束foreign key ON DELETE CASCADE ON UPDATE CASCADE

    正 文: 一,什么是foreign key,及其完整性 个人觉得,foreign key就是表与表之间的某种约定的关系,由于这种关系的存在,我们能够让表与表之间的数据,更加的完整,关连性更强.关于完整 ...

  9. MySQL外键约束_ON DELETE CASCADE/ON UPDATE CASCADE

    MySQL通过外键约束实现数据库的参照完整性,外键约束条件可在创建外键时指定,table的存储引擎只能是InnoDB,因为只有这种存储模式才支持外键. 外键约束条件有以下4种: (1)restrict ...

最新文章

  1. 品牌管理案例——添加新品牌 删除品牌 根据条件筛选品牌
  2. 湖南计算机专业专科排名2015,湖南最好的公办专科大学有哪些排名揭秘?湖南十大专科学校推荐?...
  3. Android新手入门2016(10)--GridView
  4. codeforces 118A-C语言解题报告
  5. 非线性动力学_非线性动力学特辑 低维到高维的联通者
  6. 我来谈谈小程序和工作方向
  7. Serverless Computing:现状与基础知识
  8. 「leetcode」57. 插入区间:【模拟插入】详细讲解!
  9. Objective C类方法load和initialize的区别
  10. R语言:蒙特卡洛模拟
  11. 博主个人用的duilib版本
  12. php 单词替换,单词替换 - Shiyin's note
  13. mysql 怎么解决幻读的问题
  14. 矩阵分析一子空间和特征分解
  15. 第三章 微分中值定理与导数的应用
  16. binlog2sql 安装使用
  17. 蓝桥杯 平方和(JAVA)
  18. Redis 自动过期 使用 EXPIRE、PEXPIRE:设置生存时间
  19. Python爬取美女主播图片适合初学者
  20. cesium获取模型高度_Cesium专栏-空间分析之剖面分析(附源码下载)

热门文章

  1. Rust 学习笔记——智能指针
  2. C++ 编写的DLL导出的函数名乱码含义解析
  3. GraphQL实战经验和性能问题的解决方案
  4. 是的,又一次立FLAG了
  5. *2.3.2_加入env
  6. KnockoutJS 3.X API 第五章 高级应用(2) 控制后代绑定
  7. GIS基础软件及操作(一)
  8. 《C++标准程序库》学习笔记(一)C++相关特性
  9. 实现两边定宽,中间自适应布局(三栏布局)的七种方法
  10. 【Vue】—插槽的基本语法