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.

Once you establish a UNIQUE constraint, every value in the named columns must be unique. If you try to<br />

update or insert a row with a value that already exists in a column with a UNIQUE constraint, <strong>SQL</strong> <strong>Server</strong><br />

will raise an error and reject the record.<br />

Since there is nothing novel about this (we’ve pretty much already seen it with primary keys), let’s get<br />

right to the code. Let’s create yet another table in our Accounting database. This time, it will be our<br />

Shippers table:<br />

CREATE TABLE Shippers<br />

(<br />

ShipperID int IDENTITY NOT NULL<br />

PRIMARY KEY,<br />

ShipperName varchar(30) NOT NULL,<br />

Address varchar(30) NOT NULL,<br />

City varchar(25) NOT NULL,<br />

State char(2) NOT NULL,<br />

Zip varchar(10) NOT NULL,<br />

PhoneNo varchar(14) NOT NULL<br />

UNIQUE<br />

);<br />

Now run sp_helpconstraint against the Shippers table, and verify that your Shippers table has<br />

been created with the proper constraints.<br />

Creating UNIQUE Constraints on Existing Tables<br />

Again, this works pretty much the same as with primary and foreign keys. We will go ahead and create a<br />

UNIQUE constraint on our Employees table:<br />

ALTER TABLE Employees<br />

ADD CONSTRAINT AK_EmployeeSSN<br />

UNIQUE (SSN);<br />

Chapter 6: Constraints<br />

Unlike a primary key, a UNIQUE constraint does not automatically prevent you from<br />

having a NULL value. Whether NULLs are allowed or not depends on how you set the<br />

NULL option for that column in the table. Keep in mind, however, that, if you do<br />

allow NULLs, you will be able to insert only one of them (although a NULL doesn’t<br />

equal another NULL, they are still considered to be duplicate from the perspective of<br />

a UNIQUE constraint).<br />

A quick run of sp_helpconstraint verifies that our constraint was created as planned, and tells us on<br />

which columns the constraint is active.<br />

In case you’re wondering, the AK I used in the constraint name here is for alternate key — much like<br />

we used PK and FK for primary and foreign keys. You will also often see a UQ or just U prefix used for<br />

UNIQUE constraint names.<br />

171

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

Saved successfully!

Ooh no, something went wrong!