The following table definition:
CREATE TABLE Customers( id INT NOT NULL PRIMARY KEY, name [varchar](50) )
CREATE TABLE Orders ( id INT NOT NULL PRIMARY KEY,
customer INT FOREIGN KEY
REFERENCES Customers(id) ON DELETE CASCADE )
CREATE TABLE OrderDetails ( id INT NOT NULL PRIMARY KEY,
order INT FOREIGN KEY REFERENCES Orders(id) ON DELETE CASCADE,
customer INT FOREIGN KEY REFERENCES Customers(id) ON DELETE CASCADE )
isn't possible in sql server because there are multiple cascade paths.
I thought let's create OrderDetails without the ON DELETE CASCADE
on column order
and let's see whether it is possible to enforce referential integrity when deleting an order with a trigger containing:
DELETE FROM OrderDetails
FROM Deleted d
INNER JOIN OrderDetails od
ON od.order = d.id
The trigger fires after the delete in Orders, so it is not possible (The DELETE statement conflicted with the REFERENCE constraint).
I believe the problem lies in the model design and the reference from OrderDetails to Customers is a bad design. However otherwise it would be possible to create OrderDetails for Orders that belong to different Customers.
Two questions:
- what is the best model design?
- is it nevertheless possible to use a trigger?
EDIT: I removed the reference from OrderDetails to Customers, it doesn't make any sense. This resolves all issues.