I have these 3 tables:
ConstructorEmployee
EID
(employee ID) as primary key and other key.
Project
PID
as primary key and other keys.
ProjectConstructorEmployee
PID
andEID
as foreign keys to the other tables.
Each ConstructorEmployee
can work on several Projects
. I need to create a trigger that if project has been deleted, I need to delete all ConstructorEmployee
that worked only on this project. I need to delete them from the ConstructorEmployee
table.
I'm working on SQL Server 2017.
Best Answer
I assume your table schema is similar to next one:
With two FOREIGN KEY on
ProjectConstructorEmployee
table.Now let me add some data 3 employes and 3 projects, but Employee=1 has worked only on the first Project.
Next query returns a list of employees that has worked in only one project, in this case PID=1
No, don't use a trigger, let me suggest to use an STORED PROCEDURE, it's always more clear for your and for any further developer. Or if you want to use a trigger, use a BEFORE DELETE trigger that calls this procedure.
Ok, let me try it by deleting projects 1 and 2:
Remaining employees:
Projects:
and ProjectsEmployees:
db<>fiddle here
But...are you sure you want to delete all this information?
You will lost all the Project's history, employees and projects will disappear of your database. Maybe you could set a flag like Active(Yes/No) a let this information available for whichever want to recover later.