简体   繁体   中英

SQL Server constraint on delete

I created this table:

CREATE TABLE OfficialEmployee
(
    EID Integer not null foreign key references Employee(EID),
    StartWorkingDate date not null ,
    Degree char(20) not null,
    Department char(50) not null,
    DID Integer not null foreign key references Department(DID)
);

which references the table Employee by the DID :

CREATE TABLE Employee
(   
    EID Integer not null PRIMARY KEY,
    FirstName char(30) not null,
    LastName char(30) not null,
    BirthDate date not null,
    CellPhoneNumber Integer not null,
    City char(30) not null,
    StreetName char(30) not null,
    Number Integer not null,
    Door Integer not null
);

CREATE TABLE Department 
(
    DID Integer not null PRIMARY KEY,
    Name char(30) not null,
    Description char(200) not null,
    Manage Integer not null FOREIGN KEY REFERENCES OfficialEmployee(EID)
);

and I want to make a constraint that when OfficialEmployee is deleted, the record of his in Employee will be deleted too only if he is not a manager (in the Department table) else it will (using cascade).

How can I do that?

(I'm using SQL Server)

Assuming that the description you want to avoid is 'Manager', here is a simple trigger.

CREATE TRIGGER deleteEmployeeTrigger
ON dbo.OfficialEmployee
FOR DELETE
AS
    DELETE FROM dbo.Employee
    WHERE EID IN (SELECT deleted.EID FROM deleted) 
      AND NOT EXISTS (SELECT * FROM Department 
                      WHERE Manage = deleted.EID AND Description = 'Manager') 

In SQL Server, you have to remember that deleted (and inserted can have more than one record.

So, do this using JOIN :

CREATE TRIGGER deleteEmployeeTrigger
ON dbo.OfficialEmployee
FOR DELETE AS
BEGIN
    DELETE e
        FROM dbo.Employee e JOIN
             dbo.deleted dd
             ON e.EID = dd.EID LEFT JOIN
             dbo.department d
             ON d.manage = dd.EID
    WHERE d.manage IS NULL;
END;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM