SQL 如何编辑表格以启用 CASCADE DELETE?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4454861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 08:35:27  来源:igfitidea点击:

How do I edit a table in order to enable CASCADE DELETE?

sqlsql-serversql-server-2008cascading-deletes

提问by RadiantHex

I have a table representing users. When a user is deleted I get:

我有一个代表用户的表。当用户被删除时,我得到:

DELETE statement conflicted with the REFERENCE constraint

DELETE 语句与 REFERENCE 约束冲突

Apparently, CASCADE DELETEis not as easy as I imagined in SQL Server, and the option needs to be added to the table.

显然,CASCADE DELETE在 SQL Server 中并没有我想象的那么容易,需要将选项添加到表中。

The problem is: I cannot figure out how to add the CASCADE DELETEoption.

问题是:我不知道如何添加CASCADE DELETE选项。

I'm using: SQL Server 2008. Any ideas how to do this?

我正在使用:SQL Server 2008。任何想法如何做到这一点?

回答by RC_Cleland

Read this Microsoft article first. Read Me. I use the GUI during design so here is a picture of how it is selected in SSMS. alt textThe syntax added to the foreign key is " ON DELETE CASCADE "

首先阅读这篇 Microsoft 文章。读我。我在设计期间使用 GUI,所以这里是如何在 SSMS 中选择它的图片。 替代文字添加到外键的语法是“ON DELETE CASCADE”

回答by Mr. TA

Google ALTER TABLE DROP CONSTRAINT, then ALTER TABLE ADD CONSTRAINT:

谷歌ALTER TABLE DROP CONSTRAINT,然后ALTER TABLE ADD CONSTRAINT

ALTER TABLE

更改表

Here's a quick example:

这是一个快速示例:

CREATE TABLE A 
(
 ID INTEGER NOT NULL UNIQUE
);

CREATE TABLE B 
(
 ID INTEGER NOT NULL UNIQUE
    CONSTRAINT fk__B__A 
       REFERENCES A (ID)
);

-- Oops! Forgot the CASCADE referential actions.
-- DROP the constraint then recreate it:

ALTER TABLE B DROP
   CONSTRAINT fk__B__A;

ALTER TABLE B ADD
   CONSTRAINT fk__B__A
      FOREIGN KEY (ID)
      REFERENCES A (ID)
      ON DELETE CASCADE
      ON UPDATE CASCADE;

回答by Mike Gledhill

Here's the way I would add the "cascading delete" feature to an existingforeign key in SQL Server Management Studio.

这是我将“级联删除”功能添加到SQL Server Management Studio 中现有外键的方式。

First, find your foreign key, and open it's "DROP and CREATE To" in a new Query window.

首先,找到您的外键,并在新的查询窗口中打开它的“DROP and CREATE To”。

Drop and Create

删除和创建

Then, just add "ON DELETE CASCADE" to the "ADD CONSTRAINT" command:

然后,只需将“ ON DELETE CASCADE”添加到“ ADD CONSTRAINT”命令:

On delete cascade

在删除级联

Then just hit hit the "Execute" button to run the query.

然后只需点击“执行”按钮即可运行查询。

Job done !

任务完成 !