0

假设我有一个名为 Companies 的表,它有一个 DepartmentID 列。还有一个包含 EmployeeID 列的部门表。当然,我也有一个 Employee 表。问题是我想删除一家公司,所以首先我必须删除每个部门的所有员工,然后是公司中的所有部门。级联删除不是一个选项,因此我希望使用嵌套事务。我是 SQL 新手,非常感谢您的帮助。

4

2 回答 2

4

我不确定你为什么需要在这里嵌套事务。您只需要一笔实际交易:

BEGIN TRAN

DELETE FROM Employee
    FROM Employee
    INNER JOIN Department ON Employee.DepartmentID = Department.DepartmentID
    INNER JOIN Company ON Department.CompanyID = Company.CompanyID
    WHERE Company.CompanyID = @CompanyID

DELETE FROM Department
    FROM Department
    INNER JOIN Company ON Department.CompanyID = Company.CompanyID
    WHERE Company.CompanyID = @CompanyID

DELETE FROM Company
    WHERE Company.CompanyID = @CompanyID

COMMIT TRAN

请注意双 FROM,这不是拼写错误,它是在 DELETE 中执行 JOIN 的正确 SQL 语法。

每个语句都是原子的,整个 DELETE 要么成功要么失败,这在这种情况下并不重要,因为整个批处理要么成功要么失败。

顺便说一句-我认为你的关系倒退了。Department 没有 EmployeeID,Employee 会有 DepartmentID。

于 2008-09-12T13:36:48.750 回答
0

我没有回答你的问题,但是外键要走的路,为什么它不是一个选项?

至于嵌套事务,它们是:

BEGIN
  delete from Employee where departmentId = 1;
  BEGIN
     delete from Department where companyId = 2;
     BEGIN
        delete from Company where companyId = 2;
     END
  END
END

以编程方式它看起来当然不同,但这取决于您使用的平台

于 2008-09-12T13:25:09.637 回答