触发删除有两个条件

时间:2018-12-23 00:06:45

标签: sql sql-server database

这些是与此问题相关的表格:

Employee (EID, FirstName, LastName) - father
ConstructorEmployee (EID, CompanyName, SalaryPerDay) - son
Project (PID)
ProjectsConstructorEmployees (EID, PID, ...)

我想创建一个触发器,每当有人删除项目时,它将从employee表(以及级联,匹配的构造函数employee)中删除所有构造函数employee,仅在中起作用删除的项目。

这意味着,如果员工1在项目1和2上工作,则员工2仅在项目2上工作,删除项目2后,员工2将被删除,而员工1则不会。

到目前为止,这是我尝试过的,但是我缺少了项目的唯一一部分。

------- 1 -------
CREATE TRIGGER DeleteProject
AFTER DELETE 
ON Project 
AS
    DELETE FROM Employee
    WHERE E.EID == (SELECT EID 
                    FROM ConstructorEmployee as CE
                    WHERE CE.PID == (SELECT PID FROM deleted)) 
GO

谢谢。

2 个答案:

答案 0 :(得分:2)

您需要将删除的内容包装在BEGIN / END块中。

在触发器中,您可以使用IN比较运算符来包含一个查询,该查询返回要删除的员工ID列表。

要构建id列表,您想在表ProjectsConstructorEmployees中查找所有在该项目上工作过的雇员,然后使用相关查询和{ {1}}子句。

NOT EXIST

NB:为了使您的逻辑有意义,您必须在此步骤之后添加另一步骤,以无条件删除表CREATE TRIGGER DeleteProject AFTER DELETE ON Project AS BEGIN DELETE FROM Employee WHERE E.EID IN ( SELECT PCE.EID FROM DELETED DEL INNER JOIN ProjectsConstructorEmployees PCE ON PCE.PID = DEL.PID WHERE NOT EXISTS ( SELECT 1 FROM ProjectsConstructorEmployees WHERE EID = PCE.EID AND PID != DEL.PID ) ) END 中所有与项目相关的记录。曾经在两个不同项目上工作过的其他员工永远不会消失。

ProjectsConstructorEmployees

答案 1 :(得分:-1)

希望有帮助。

   CREATE TABLE Employee(EID INT,FirstName varchar(500),LastName varchar(50))

GO

   CREATE TABLE ConstructorEmployee(EID INT,CompanyName varchar(500),SalaryPerDay bigint)

GO

   CREATE TABLE Project(PID INT)

GO

  CREATE TABLE ProjectsConstructorEmployees(EID int ,PID INT)

GO

   INSERT INTO Employee
   SELECT 1,'MANI','KANDAN'
   UNION
   SELECT 2,'RAM','CHARAN'
   UNION
   SELECT 3,'RAGU','NATH'

GO        插入到ConstructorEmployee中        选择1,'HST',20        联盟        选择2,'RRR',50        联盟        SELECT 3,“ FRT”,90

GO

  INSERT INTO PROJECT 
  SELECT 9
  UNION
  SELECT 10  
  UNION
  SELECT 13

GO       INSERT INTO ProjectsConstructorEmployees       选择1.9       联盟       选择1,10       联盟       选择2,13       联盟       选择3,9       联盟       选择3,10

GO

 SELECT * FROM Employee
 SELECT * FROM ConstructorEmployee
 SELECT * FROM Project
 SELECT * FROM ProjectsConstructorEmployees

GO

 CREATE TRIGGER PROJ_DEL
 ON Project
 FOR  DELETE
 AS
 DECLARE @A TABLE (A INT)
 INSERT INTO @A 
 SELECT * FROM DELETED
 DELETE S FROM ConstructorEmployee S WHERE EID IN(
 SELECT D.EID FROM ProjectsConstructorEmployees D JOIN (
 SELECT A.* FROM ProjectsConstructorEmployees A INNER JOIN @A  B ON
 ( A.PID=B.A) INNER JOIN ConstructorEmployee C ON (A.EID = C.EID))F ON 
 (D.EID=F.EID)
 GROUP BY D.EID 
 HAVING COUNT(D.EID)=1)  

GO

  DELETE FROM PROJECT WHERE PID=10---EID 10 MAPPED TO MORE THAN ONE PROJ SO 
  IT WILL NOT ALLOW FOR DELETE

  DELETE FROM PROJECT WHERE PID=13---EID 13 MAPPED TO  ONLY ONE PROJ SO IT 
  WILL  ALLOW FOR DELETE