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.

When we run this, we have a problem:<br />

Msg 547, Level 16, State 0, Line 1<br />

The ALTER TABLE statement conflicted with the CHECK constraint<br />

“CN_CustomerPhoneNo”. The conflict occurred in database “Accounting”, table<br />

“dbo.Customers”, column ‘Phone’.<br />

<strong>SQL</strong> <strong>Server</strong> does not create the constraint unless the existing data meets the constraint criteria. To get<br />

around this long enough to install the constraint, either we need to correct the existing data or we must<br />

make use of the WITH NOCHECK option in our ALTER statement. To do this, we just add WITH NOCHECK to<br />

the statement as follows:<br />

ALTER TABLE Customers<br />

WITH NOCHECK<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]‘);<br />

Now if we run our same INSERT statement again (remember it inserted without a problem last time), the<br />

constraint works and the data is rejected:<br />

Msg 547, Level 16, State 0, Line 1<br />

The ALTER TABLE statement conflicted with the CHECK constraint<br />

“CN_CustomerPhoneNo”. The conflict occurred in database “Accounting”, table<br />

“dbo.Customers”, column ‘Phone’.<br />

However, if we modify our INSERT statement to adhere to our constraint and then re-execute it, the row<br />

will be inserted normally:<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 />

‘(800) 555-1212’,<br />

‘931234567’,<br />

GETDATE());<br />

Chapter 6: Constraints<br />

177

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

Saved successfully!

Ooh no, something went wrong!