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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 6: Constraints<br />

So we have a CustomerID of 1 (your number may be different depending on what experimentation you’ve<br />

done). We’ll take that number and use it in our next INSERT (into Orders, finally). Let’s insert an order<br />

for CustomerID 1:<br />

INSERT INTO Orders<br />

(CustomerNo, OrderDate, EmployeeID)<br />

VALUES<br />

(1, GETDATE(), 1);<br />

This time, things should work fine.<br />

It’s worth noting that the reason we don’t still get an error here is that we already<br />

inserted that primer row in the Employees table; otherwise, we would have needed<br />

to get a row into that table before <strong>SQL</strong> <strong>Server</strong> would have allowed the insert into<br />

Orders (remember that Employees foreign key?).<br />

At this point, we’re ready for our insert into the OrderDetails table. Just to help with a CASCADE example<br />

we’re going to be doing in a moment, we’re actually going to insert not one, but two rows:<br />

INSERT INTO OrderDetails<br />

VALUES<br />

(1, ‘4X4525’, ‘This is a part’, 25.00, 2)<br />

INSERT INTO OrderDetails<br />

VALUES<br />

(1, ‘0R2400’, ‘This is another part’, 50.00, 2);<br />

So, let’s verify things by running a SELECT:<br />

SELECT OrderID, PartNo FROM OrderDetails;<br />

This gets us back to our expected two rows:<br />

OrderID PartNo<br />

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

1 0R2400<br />

1 4X4525<br />

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

Now that we have our data entered, let’s look at the effect a CASCADE has on the data. We’ll delete a row<br />

from the Orders table, and then see what happens in OrderDetails:<br />

USE Accounting<br />

-- First, let’s look at the rows in both tables<br />

SELECT *<br />

FROM Orders;<br />

SELECT *<br />

167

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

Saved successfully!

Ooh no, something went wrong!