Erik Åstrand
Erik Åstrand

Reputation: 379

Deleting data from multiple tables

create table Person(
    SSN INT,
    Name VARCHAR(20),
    primary key(SSN)
);
create table Company(
CompanyID INT,
Name VARCHAR(20)
primary key(SSN)

create table Car(
    PlateNr INT,
    Model VARCHAR(20),
    primary key(PlateNr)
);

create table CarOwner(
    SSN INT,
    PlateNr INT,
    primary key(SSN, PlateNR)
    foreign key(SSN) references Person (SSN),
    foreign key(PlateNr) references Car (PlateNr)
);

create table CompanyWorker(
    SSN INT,
    CompanyID INT
    primary key(SSN, CompanyID),
    foreign key(SSN) references Person (SSN),
    foreign key(CompanyID) references Company (CompanyID)
);

Insert into Person(SSN, Name) VALUES ('123456789','Max');
Insert into Person(SSN, Name) VALUES ('123456787','John');
Insert into Person(SSN, Name) VALUES ('123456788','Tom');

insert into Company(CompanyID, Name) VALUES('1','IKEA');
insert into Company(CompanyID, Name) VALUES('2','Starbucks');

Insert into Car(PlateNr, Model) VALUES ('123ABC','Volvo');
Insert into Car(PlateNr, Model) VALUES ('321CBA','Toyota');
Insert into Car(PlateNr, Model) VALUES ('333AAA','Honda');

Insert into CarOwner(SSN, PlateNr) VALUES ('123456789','123ABC');
Insert into CarOwner(SSN, PlateNr) VALUES ('123456787','333AAA');
Insert into CarOwner(SSN, PlateNr) VALUES ('123456788','321CBA');

insert into CompanyWorker(SSN, CompanyID) VALUES('123456789','1');
insert into CompanyWorker(SSN, CompanyID) VALUES('123456787','1');

This is my tables and insert into those tables and the problem I'm having is deleting a person. I want to be able to delete a person from the "Person" table, example

DELETE FROM Person WHERE SSN = '123456789';

But the problem is that I have to delete the person from all the other tables that said person have a relation with. Person have relations with CarOwner and CompanyWorker. Sure, I could simply execute 3 seperate delete-statements at once:

DELETE FROM Person WHERE SSN = '123456789';
DELETE FROM CarOwner WHERE SSN = '123456789';
DELETE FROM CompanyWorker WHERE SSN = '123456789';

But then if this SSN doesn't exist in CompanyWorker I will run into problems since it's trying to delete something that doesnt exist there. So I need to somehow be able to check if it exists first before deleting somehow, this is my problem.

Upvotes: 0

Views: 1321

Answers (1)

adyusuf
adyusuf

Reputation: 825

If you use MSSQL as database engine, you can ALTER TABLE to add a FOREIGN CONSTRAINT with ON DELETE CASCADE

ALTER TABLE CarOwner
    ADD CONSTRAINT FK_CarOwner_SSN 
        FOREIGN KEY (SSN) 
        REFERENCES Person (SSN) 
        ON DELETE CASCADE 

Upvotes: 1

Related Questions