Suppose I have a table called Companies that has a DepartmentID column. There's also a Departaments table that has as EmployeeID column. Of course I have an Employee table as well. The problem is that I want to delete a company, so first i have to delete all the employees for every departament and then all the departaments in the company. Cascade Delete is not an option, therefore i wish to use nested transactions. I'm new to SQL so I would appreciate your help.
A:
I'm not answering your question, but foreign Keys is the way to go, why is it not an option?
As for nested transactions they are:
BEGIN
delete from Employee where departmentId = 1;
BEGIN
delete from Department where companyId = 2;
BEGIN
delete from Company where companyId = 2;
END
END
END
Programmatically it looks different of course, but that'd depend on the platform you are using
Vinko Vrsalovic
2008-09-12 13:25:09
+3
A:
I'm not sure why you need nested transactions here. You only need one actual transaction:
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
Note the double FROM, that is not a typo, it's the correct SQL syntax for performing a JOIN in a DELETE.
Each statement is atomic, either the entire DELETE will succeed or fail, which isn't that important in this case because the entire batch will either succeed or fail.
BTW- I think you had your relationships backwards. The Department would not have an EmployeeID, the Employee would have a DepartmentID.
Brannon
2008-09-12 13:36:48
Your queries can be optimized to remove the INNER JOINs on Company. Or would this be something SQL Server would do automatically?
rpetrich
2008-09-12 14:11:08
You're right. I just added them to be explicit, but you could change your WHERE clause to:WHERE Department.CompanyID = @CompanyID
Brannon
2008-09-12 16:05:32