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

CHECK Constraints<br />

172<br />

The nice thing about CHECK constraints is that they are not restricted to a particular column. They can be<br />

related to a column, but they can also be essentially table related in that they can check one column<br />

against another, as long as all the columns are within a single table and the values are for the same row<br />

being updated or inserted. They can also check that any combination of column values meets a criterion.<br />

The constraint is defined using the same rules that you would use in a WHERE clause. Examples of the<br />

criteria for a CHECK constraint include:<br />

Goal <strong>SQL</strong><br />

Limit Month column to<br />

appropriate numbers<br />

BETWEEN 1 AND 12<br />

Proper SSN formatting LIKE ‘[0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]’<br />

Limit to a specific list of<br />

Shippers<br />

Price must be positive UnitPrice >= 0<br />

Referencing another<br />

column in the same row<br />

IN (‘UPS’, ‘Fed Ex’, ‘USPS’)<br />

ShipDate >= OrderDate<br />

This really only scratches the surface, and the possibilities are virtually endless. Almost anything you<br />

could put in a WHERE clause, you can also put in your constraint. What’s more, CHECK constraints are<br />

very fast performance-wise as compared to the alternatives (rules and triggers).<br />

Still building on our Accounting database, let’s add a modification to our Customers table to check for a<br />

valid date in our DateInSystem field (you can’t have a date in the system that’s in the future):<br />

ALTER TABLE Customers<br />

ADD CONSTRAINT CN_CustomerDateInSystem<br />

CHECK<br />

(DateInSystem

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

Saved successfully!

Ooh no, something went wrong!