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
How do I edit a table in order to enable CASCADE DELETE?
提问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 DELETE
is 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 DELETE
option.
问题是:我不知道如何添加CASCADE DELETE
选项。
I'm using: SQL Server 2008. Any ideas how to do this?
我正在使用:SQL Server 2008。任何想法如何做到这一点?
回答by RC_Cleland
回答by Mr. TA
Google ALTER TABLE DROP CONSTRAINT
, then ALTER TABLE ADD CONSTRAINT
:
谷歌ALTER TABLE DROP CONSTRAINT
,然后ALTER TABLE ADD CONSTRAINT
:
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”。
Then, just add "ON DELETE CASCADE
" to the "ADD CONSTRAINT
" command:
然后,只需将“ ON DELETE CASCADE
”添加到“ ADD CONSTRAINT
”命令:
Then just hit hit the "Execute" button to run the query.
然后只需点击“执行”按钮即可运行查询。
Job done !
任务完成 !