我有两张桌子:
CREATE TABLE [dbo].[AdminTest] (
[AdminTestId] INT IDENTITY (1, 1) NOT NULL,
[Title] NVARCHAR (100) NOT NULL,
CONSTRAINT [PK_AdminTest] PRIMARY KEY CLUSTERED ([AdminTestId] ASC)
);
GO
CREATE NONCLUSTERED INDEX [Test_ExamId_IX]
ON [dbo].[AdminTest]([ExamId] ASC);
CREATE TABLE [dbo].[AdminTestQuestion] (
[AdminTestQuestionId] INT IDENTITY (1, 1) NOT NULL,
[AdminTestId] INT NOT NULL,
[QuestionUId] UNIQUEIDENTIFIER NOT NULL,
CONSTRAINT [PK_AdminTestQuestion] PRIMARY KEY CLUSTERED ([AdminTestQuestionId] ASC),
CONSTRAINT [FK_AdminTestQuestionAdminTestId] FOREIGN KEY ([AdminTestId]) REFERENCES [dbo].[AdminTest] ([AdminTestId])
);
GO
CREATE NONCLUSTERED INDEX [AdminTestQuestion_AdminTestId_IX]
ON [dbo].[AdminTestQuestion]([AdminTestId] ASC);
是否有某些方法可以更改表的定义,以便在从AdminTest删除行时,删除该测试的AdminTestQuestions中的所有子行?
答案 0 :(得分:2)
您可以将ON DELETE CASCADE
添加到外键约束中;
CONSTRAINT [FK_AdminTestQuestionAdminTestId]
FOREIGN KEY ([AdminTestId]) REFERENCES [dbo].[AdminTest] ([AdminTestId])
ON DELETE CASCADE
我可能不需要指出,从长远来看,这不一定是个好主意,因为它会对您的数据进行隐式更改,而其他用户可能不知道。请谨慎使用。