我有这些表格:
CREATE TABLE [dbo].[ObjectiveDetail] (
[ObjectiveDetailId] INT IDENTITY (1, 1) NOT NULL,
[ObjectiveId] INT NOT NULL,
[Number] INT NOT NULL,
[Text] NVARCHAR (MAX) NOT NULL,
CONSTRAINT [PK_ObjectiveDetail] PRIMARY KEY CLUSTERED ([ObjectiveDetailId] ASC),
CONSTRAINT [FK_ObjectiveDetailObjective] FOREIGN KEY ([ObjectiveId]) REFERENCES [dbo].[Objective] ([ObjectiveId])
);
CREATE TABLE [dbo].[ObjectiveTopic] (
[ObjectiveDetailId] INT NOT NULL,
[SubTopicId] INT NOT NULL,
CONSTRAINT [PK_ObjectiveTopicObjectiveDetail] PRIMARY KEY CLUSTERED ([ObjectiveDetailId] ASC, [SubTopicId] ASC),
CONSTRAINT [FK_ObjectiveTopicObjectiveDetail] FOREIGN KEY ([ObjectiveDetailId]) REFERENCES [dbo].[ObjectiveDetail] ([ObjectiveDetailId]),
CONSTRAINT [FK_ObjectiveTopicSubTopic] FOREIGN KEY ([SubTopicId]) REFERENCES [dbo].[SubTopic] ([SubTopicId])
);
GO
CREATE UNIQUE NONCLUSTERED INDEX [NobjectiveDetail_Number_IX]
ON [dbo].[ObjectiveDetail]([ObjectiveId] ASC, [Number] ASC);
GO
CREATE NONCLUSTERED INDEX [Objective_ObjectiveDetailId_IX]
ON [dbo].[ObjectiveDetail]([ObjectiveDetailId] ASC);
我想要做的是删除一个ObjectiveDetail。但是如果ObjectiveTopic表中有一行,则删除失败。
当ObjectiveDetail行被删除时,是否还有一些方法可以删除ObjectiveTopic表中的另一行?
答案 0 :(得分:2)
更改约束,使其启用ON DELETE CASCADE。
ALTER TABLE dbo.LocalData
DROP CONSTRAINT FK_ReferenceDataLocaldata
ALTER TABLE dbo.LocalData
ADD CONSTRAINT FK_ReferenceDataLocaldata_Cascade
FOREIGN KEY (ForeignID) REFERENCES dbo.ReferenceData(ForeignPK) ON DELETE CASCADE
基本上你所做的就是在添加约束命令
的末尾添加ON DELETE CASCADE要将此问题应用于您的问题,我们需要更改
ALTER TABLE ObjectiveTopic
DROP CONSTRAINT [FK_ObjectiveTopicObjectiveDetail]
到
ALTER TABLE ObjectiveTopic
CREATE CONSTRAINT [FK_ObjectiveTopicObjectiveDetail] FOREIGN KEY ([ObjectiveDetailId]) REFERENCES [dbo].[ObjectiveDetail] ([ObjectiveDetailId]) ON DELETE CASCASE
答案 1 :(得分:0)
ALTER TABLE dbo.ReferenceData DROP CONSTRAINT FK_MyTable
ALTER TABLE dbo.LocalData
ADD CONSTRAINT FK_ReferenceDataLocaldata_Cascade
FOREIGN KEY (ForeignID) REFERENCES dbo.ReferenceData(ForeignPK)
ON DELETE CASCADE