Frage

I am using SQL Server 2012 and I have the following DDL:

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])
);

Is there a way I can make this so that when I delete a row in the Test table then all rows with that TestId are deleted from the TestQuestion table?

War es hilfreich?

Lösung

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 }

Andere Tipps

As other commentators have said, the cascading foreign key is the best way to go. If you need more complicated logic, however, you could use a FOR DELETE trigger.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top