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 />

Try running a SELECT on the Customers table at this point. You’ll see data that both does and does not<br />

adhere to our CHECK constraint criterion:<br />

SELECT CustomerNo, CustomerName, Phone FROM Customers;<br />

CustomerNo CustomerName Phone<br />

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

1 Billy Bob’s Shoes (360) 555-1234<br />

2 Customer1 553-1212<br />

3 MyCust 555-1212<br />

5 MyCust (800) 555-1212<br />

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

The old data is retained for back reference, but any new data is restricted to meeting the new criteria.<br />

Temporarily Disabling an Existing Constraint<br />

178<br />

All right, so you understand why we need to be able to add new constraints that do not check old data,<br />

but why would we want to temporarily disable an existing constraint? Why would we want to let data<br />

that we know is bad be added to the database? Actually, the most common reason is basically the same<br />

reason for which we make use of the WITH NOCHECK option — old data.<br />

Old data doesn’t just come in the form of data that has already been added to your database. It may also<br />

be data that you are importing from a legacy database or some other system. Whatever the reason, the<br />

same issue still holds: You have some existing data that doesn’t match up with the rules, and you need<br />

to get it into the table.<br />

Certainly one way to do this would be to drop the constraint, add the desired data, and then add the<br />

constraint back using a WITH NOCHECK. But what a pain! Fortunately, we don’t need to do that. Instead,<br />

we can run an ALTER statement with an option called NOCHECK that turns off the constraint in question.<br />

Here’s the code that disables the CHECK constraint that we just added in the previous section:<br />

ALTER TABLE Customers<br />

NOCHECK<br />

CONSTRAINT CN_CustomerPhoneNo;<br />

Now we can run that INSERT statement again — the one we proved wouldn’t work if the constraint<br />

were active:<br />

INSERT INTO Customers<br />

(CustomerName,<br />

Address1,<br />

Address2,<br />

City,<br />

State,<br />

Zip,<br />

Contact,<br />

Phone,

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

Saved successfully!

Ooh no, something went wrong!