继续问题Get all of the rows involved between tables relationships,现在我必须删除这些代码的所有行。我解释一下:
我有一个带有下表的 SQL Server 2016:
CREATE TABLE [dbo].[Code] (
[CodeId] INT IDENTITY (1, 1) NOT NULL,
[Serial] VARCHAR(20) NOT NULL,
[AggregationLevelId] TINYINT NOT NULL,
[CommissioningFlag] TINYINT NOT NULL,
[ ... ]
CONSTRAINT [PK_CODE] PRIMARY KEY CLUSTERED ([CodeId] ASC),
CONSTRAINT [UC_CODE_SERIAL] UNIQUE NONCLUSTERED ([Serial] ASC),
CONSTRAINT [FK_Code_AggregationLevelConfiguration]
FOREIGN KEY ([AggregationLevelId])
REFERENCES [dbo].[AggregationLevelConfiguration] ([AggregationLevelConfigurationId])
)
CREATE TABLE [dbo].[Aggregation] (
[AggregationId] INT NOT NULL,
CONSTRAINT [PK_AGGREGATIONS] PRIMARY KEY CLUSTERED ([AggregationId] ASC),
CONSTRAINT [FK_Aggregation_Code]
FOREIGN KEY ([AggregationId])
REFERENCES [dbo].[Code] ([CodeId])
)
CREATE TABLE [dbo].[AggregationChildren] (
[AggregationChildrenId] INT NOT NULL,
[AggregationId] INT NOT NULL,
[Position] INT NOT NULL,
CONSTRAINT [PK_AGGREGATION_CHILDS] PRIMARY KEY CLUSTERED ([AggregationChildrenId] ASC),
CONSTRAINT [FK_AggregationChildren_Code]
FOREIGN KEY ([AggregationChildrenId])
REFERENCES [dbo].[Code] ([CodeId]),
CONSTRAINT [FK_AggregationChildren_Aggregation]
FOREIGN KEY ([AggregationId])
REFERENCES [dbo].[Aggregation] ([AggregationId]) ON DELETE CASCADE
)
Aggregation
并AggregationChildren
表示表中行之间的关系Code
。
聚合将有 1 个或多个子聚合。而且,聚合子项中的代码可以有 0 个或多个聚合子项。
它是这样的:
Code1
|___________________
| |
Code2 Code3
|________ |________________
| | | | |
Code4 Code5 Code6 Code7 Code8
以上都是Code.Serial
价值观。
Code.CodeId
这些连续出版物的所有值都在和的Aggregation
表Code1
中。Code2
Code3
并且,对于那些连续剧,Code2
、Code3
、Code4
、Code5
、Code6
、Code7
和Code8
在AggregationChildren
表中。
Aggregation
我需要从和AggregationChildren
表中删除那些连续出版物的行。
使用上一个问题的答案,我尝试这样做:
DECLARE @Serial VARCHAR(20) = 'Code1';
;WITH rc AS
(
SELECT AggregationId Id
FROM dbo.Aggregation
WHERE AggregationId = (SELECT CodeId FROM dbo.Code WHERE Serial = @Serial)
UNION ALL
SELECT ac.AggregationChildrenId Id
FROM dbo.AggregationChildren ac
JOIN rc
ON ac.AggregationId = rc.Id
)
UPDATE c
SET CommissioningFlag = 130
FROM dbo.Code c
JOIN rc
ON c.CodeId = rc.Id;
GO
Delete ag from dbo.Aggregation ag
inner join rc
on ag.AggregationId = rc.Id;
但我不知道如何使用DELETE FROM
withrc
语句。但我想我只需要Codes
在Aggregation
和中的那些AggregationChildren
。也许我需要修改With
语句以首先获取表中的行,Aggregation
因为我有一个ON DELETE CASCADE
inAggregationChildren
表。
如何从Aggregation
表中删除所有代码?
根据外键中有规则的表架构
ON DELETE CASCADE
,FK_AggregationChildren_Aggregation
您只能删除“聚合”表的受影响记录。使用相同的递归查询来获取行,但添加子项的 AggregationID,然后删除不同的 AggregationId 代码。
这是结果:
db<>fiddle here