从父级删除时,SQL Server 对所有子记录执行删除

SQL Server perform a delete on all child records when deleting from a parent(从父级删除时,SQL Server 对所有子记录执行删除)
本文介绍了从父级删除时,SQL Server 对所有子记录执行删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 3 张桌子:

Create TABLE Subjects
(
    SubjectID INT PRIMARY KEY NOT NULL IDENTITY(1,1),
    SubjectName VARCHAR(20) NOT NULL,
    ClassID VARCHAR(10) FOREIGN KEY REFERENCES Classes(ClassID) NOT NULL
);

Create TABLE Topic
( 
    TopicID INT PRIMARY KEY NOT NULL IDENTITY(1,1),
    TopicName VARCHAR(100),
    SubjectID INT FOREIGN KEY REFERENCES Subjects(SubjectID)
); 

Create Table Worksheet
(
    WorksheetName varchar(100) PRIMARY KEY,
    TopicID INT Foreign KEY References Topic(TopicID),
    Num_Q INT NOT NULL,
    W_Type varchar(30)
);

每一个都是一对多的关系.当我尝试从 Subjects 中删除时,我得到了一个很好的外键约束.我想知道的是如何解决这个问题并执行查询以级联样式删除所有相关方面.我查了一下,但我不确定它是如何工作的,似乎有多个查询.创建触发器会更好还是有一个基本的级联功能来完成所有工作?我正在使用 Visual Studio 执行查询,但不确定执行此类任务的选项在哪里?

Each one is a one to many relationship. When I try to delete from Subjects I get a foreign key constraint which is fine. What I want to know is how to get around this and perform a query to delete all relating aspects in a cascading style. I looked it up and there's but I am not sure how it works there seems to be multiple queries. Would it be better to create a trigger or is there a basic cascading function to do it all? I'm using visual studio to perform queries but not sure where the options to perform tasks like this are?

推荐答案

您可以在外键定义之后添加ON DELETE CASCADE:

You can add the ON DELETE CASCADE right after the foreign key definition:

Create TABLE Subjects (
    SubjectID INT PRIMARY KEY NOT NULL IDENTITY(1, 1),
    SubjectName VARCHAR(20) NOT NULL,
    ClassID VARCHAR(10) NOT NULL
        FOREIGN KEY REFERENCES Classes(ClassID) ON DELETE CASCADE
);

如果愿意,您也可以将其定义为单独的约束,在 CREATE TABLE 语句中或使用 ALTER TABLE ADD CONSTRAINT.

You can also define it as a separate constraint, if you like, either within the CREATE TABLE statement or using ALTER TABLE ADD CONSTRAINT.

这篇关于从父级删除时,SQL Server 对所有子记录执行删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)