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

Ignoring Bad Data When You Create the Constraint<br />

176<br />

All this syntax has been just fine for the circumstances in which you create the constraint at the same<br />

time as you create the table. Quite often, however, data rules are established after the fact. Let’s say, for<br />

instance, that you missed something when you were designing your database, and you now have some<br />

records in an Invoicing table that show a negative invoice amount. You might want to add a rule that<br />

won’t let any more negative invoice amounts into the database, but at the same time, you want to preserve<br />

the existing records in their original state.<br />

To add a constraint that won’t apply to existing data, you make use of the WITH NOCHECK option when<br />

you perform the ALTER TABLE statement that adds your constraint. As always, let’s look at an example.<br />

The Customers table we created in the Accounting database has a field called Phone. The Phone field<br />

was created with a data type of char because we expected all of the phone numbers to be of the same<br />

length. We also set it with a length of 15 in order to ensure that we have enough room for all the formatting<br />

characters. However, we have not done anything to make sure that the records inserted into the<br />

database do indeed match the formatting criteria that we expect. To test this out, we’ll insert a record in<br />

a format that is not what we’re expecting, but might be a very honest mistake in terms of how someone<br />

might enter a phone number:<br />

INSERT INTO Customers<br />

(CustomerName,<br />

Address1,<br />

Address2,<br />

City,<br />

State,<br />

Zip,<br />

Contact,<br />

Phone,<br />

FedIDNo,<br />

DateInSystem)<br />

VALUES<br />

(‘MyCust’,<br />

‘123 Anywhere’,<br />

‘’,<br />

‘Reno’,<br />

‘NV’,<br />

80808,<br />

‘Joe Bob’,<br />

‘555-1212’,<br />

‘931234567’,<br />

GETDATE());<br />

Now let’s add a constraint to control the formatting of the Phone field:<br />

ALTER TABLE Customers<br />

ADD CONSTRAINT CN_CustomerPhoneNo<br />

CHECK<br />

(Phone LIKE ‘([0-9][0-9][0-9]) [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]‘);

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

Saved successfully!

Ooh no, something went wrong!