删除父行时如何删除子行?

时间:2014-03-10 08:53:58

标签: sql-server sql-server-2012

我有以下DDL:

CREATE TABLE [dbo].[Test] (
    [UserId]                NVARCHAR (128) NOT NULL,
    [TestId]                INT            IDENTITY (1, 1) NOT NULL,
    [ExamId]                INT            NOT NULL,
    [Title]                 NVARCHAR (100) NULL,
    [Status]                INT            NOT NULL,
    CONSTRAINT [PK_Test] PRIMARY KEY CLUSTERED ([TestId] ASC),
    CONSTRAINT [FK_TestExam] FOREIGN KEY ([ExamId]) REFERENCES [dbo].[Exam] ([ExamId])
);


CREATE TABLE [dbo].[TestQuestion] (
    [TestQuestionId] INT           IDENTITY (1, 1) NOT NULL,
    [TestId]         INT           NOT NULL,
    [ThisAnswered]   BIT           DEFAULT ((0)) NULL,
    CONSTRAINT [PK_TestQuestion] PRIMARY KEY CLUSTERED ([TestQuestionId] ASC),
    CONSTRAINT [FK_TestQuestion_Test] FOREIGN KEY ([TestId]) REFERENCES [dbo].[Test] ([TestId])
);


GO
CREATE NONCLUSTERED INDEX [TestQuestionTest_TestId_IX]
    ON [dbo].[TestQuestion]([TestId] ASC);

我试图删除父测试,但它给了我一个错误。有没有办法可以修改它,这样当我从Test表中删除测试时它会自动删除TestQuestion表中的所有记录?

1 个答案:

答案 0 :(得分:4)

你只需要一个级联删除

CONSTRAINT [FK_TestQuestion_Test] FOREIGN KEY ([TestId]) REFERENCES [dbo].[Test] ([TestId]) 
ON DELETE CASCADE

修改

ALTER TABLE [dbo].[TestQuestion] drop constraint [FK_TestQuestion_Test];

ALTER TABLE [dbo].[TestQuestion]
ADD CONSTRAINT [FK_TestQuestion_Test] FOREIGN KEY ([TestId]) REFERENCES [dbo].[Test] ([TestId]) ON DELETE CASCADE;

请参阅SqlFiddle