17.06.2013 Views

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 6: Constraints<br />

168<br />

FROM OrderDetails;<br />

-- Now, let’s delete the Order record<br />

DELETE Orders<br />

WHERE OrderID = 1;<br />

-- Finally, look at both sets of data again<br />

-- and see the CASCADE effect<br />

SELECT *<br />

FROM Orders;<br />

SELECT *<br />

FROM OrderDetails;<br />

This yields some interesting results:<br />

OrderID CustomerNo OrderDate EmployeeID<br />

--------- ------------ -------------------- --------------<br />

1 1 2000-07-13 22:18:00 1<br />

(1 row(s) affected)<br />

OrderID PartNo Description UnitPrice Qty<br />

--------- ------- --------------------- ------------ ----<br />

1 0R2400 This is another part 50.0000 2<br />

1 4X4525 This is a part 25.0000 2<br />

(2 row(s) affected)<br />

(1 row(s) affected)<br />

OrderID CustomerNo OrderDate EmployeeID<br />

-------- ----------- ------------ -----------------------<br />

(0 row(s) affected)<br />

OrderID PartNo Description UnitPrice Qty<br />

---------- ----------- --------------- ------------ --------<br />

(0 row(s) affected)<br />

Notice that even though we issued a DELETE against the Orders table only, the DELETE also cascaded to<br />

our matching records in the OrderDetails table. Records in both tables were deleted. If we had defined<br />

our table with a CASCADE update and updated a relevant record, then that, too, would have been propagated<br />

to the child table.<br />

It’s worth noting that there is no limit to the depth that a CASCADE action can reach. For example, if we<br />

had a ShipmentDetails table that referenced rows in OrderDetails with a CASCADE action, then<br />

those, too, would have been deleted just by our one DELETE in the Orders table.<br />

This is actually one of the danger areas of cascading actions. It’s very, very easy to not realize all the different<br />

things that one DELETE or UPDATE statement can do in your database. For this and other reasons,<br />

I’m not a huge fan of cascading actions. They allow people to get lazy, and that’s something that’s<br />

not usually a good thing when doing something like deleting data!

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!