SQL:当子元素不存在时删除父元素

时间:2017-06-12 07:49:35

标签: sql stored-procedures parent-child

我有两张桌子:

tblEmployee

EmployeeID (PK), Name, Age, Department

tblDesignation

EmployeeID(FK), Designation, DesignationID

只有在指定表中没有记录时,我才需要帮助编写一个存储过程来删除员工记录。 (仅在未指定指定时删除employeeID)

我不确定是否应该使用ON DELETE RESTRICT约束或NOT EXISTS子句。

2 个答案:

答案 0 :(得分:1)

那么你可以为你的目的拥有以下代码。请原谅语法

create procedure usp_deleteemployee
as 
begin
    delete from tblEmployee 
    where id not in (select empid from tblDesignation);
end

或者你也可以尝试存在。不确定语法

DELETE tblEmployee 
FROM tblEmployee 
WHERE NOT EXISTS (SELECT 1 
                  FROM tblDesignation 
                  WHERE tblEmployee.Id = tblDesignation.empid)

答案 1 :(得分:0)

您可以尝试下面的内容。

DELETE
E
FROM
tblEmployee E
LEFT JOIN tblDesignation D
ON E.EmployeeID = D.EmployeeID
WHERE
D.EmployeeID IS NULL

希望这有助于!!