just provide ON DELETE CASCADE
to your Foreign Key of Child Table
(TestQuestion.TestId
), so it will delete child record directly when parent record is deleted.
CREATE TABLE [dbo].[Test] (
[TestId] INT IDENTITY (1, 1) NOT NULL,
[Title] NVARCHAR (100) NULL,
CONSTRAINT [PK_Test] PRIMARY KEY CLUSTERED ([TestId] ASC)
);
CREATE TABLE [dbo].[TestQuestion] (
[TestId] INT NOT NULL,
[TestQuestionId] INT NOT NULL,
[QuestionUId] CHAR (6) NOT NULL,
CONSTRAINT [PK_TestQuestion] PRIMARY KEY CLUSTERED ([TestId] ASC, [TestQuestionId] ASC),
CONSTRAINT [FK_TestQuestionTest] FOREIGN KEY ([TestId]) REFERENCES [dbo].[Test] ([TestId]) ON DELETE CASCADE
);
Actually you can have many option with DELETE
(and UPDATE
also) like:
.
For Delete
ON DELETE { NO ACTION | CASCADE | SET NULL | SET DEFAULT }
.
For Update
ON UPDATE { NO ACTION | CASCADE | SET NULL | SET DEFAULT }