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.

Do we want two customers to have the same CustomerNo? Definitely not. It makes perfect sense for a<br />

CustomerNo to be used as an identifier for a customer. Indeed, such a system has been used for years, so<br />

there’s really no sense in reinventing the wheel here.<br />

To alter our CREATE TABLE statement to include a PRIMARY KEY constraint, we just add in the constraint<br />

information right after the column(s) that we want to be part of our primary key. In this case, we<br />

would use:<br />

USE Accounting;<br />

CREATE TABLE Customers<br />

(<br />

CustomerNo int IDENTITY NOT NULL<br />

PRIMARY KEY,<br />

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

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

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

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

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

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

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

Phone char(15) NOT NULL,<br />

FedIDNo varchar(9) NOT NULL,<br />

DateInSystem smalldatetime NOT NULL<br />

);<br />

Since this table already exists in our Accounting database (as we left it at the end of Chapter 5), we need<br />

to also drop the table prior to running the CREATE TABLE script (i.e., DROP TABLE Customers). Notice<br />

that we altered one line (all we did was remove the comma) and added some code on a second line for<br />

that column. It was easy! Again, we just added one simple keyword (OK, so it’s two words, but they<br />

operate as one) and we now have ourselves a primary key.<br />

Creating a Primary Key on an Existing Table<br />

Now, what if we already have a table and we want to set the primary key? That’s also easy. We’ll do that<br />

for our Employees table:<br />

USE Accounting<br />

ALTER TABLE Employees<br />

ADD CONSTRAINT PK_EmployeeID<br />

PRIMARY KEY (EmployeeID);<br />

Our ALTER command tells <strong>SQL</strong> <strong>Server</strong>:<br />

❑ That we are adding something to the table (we could also be dropping something from the table<br />

if we so chose)<br />

❑ What it is that we’re adding (a constraint)<br />

❑ What we want to name the constraint (to allow us to address the constraint directly later)<br />

❑ The type of constraint (PRIMARY KEY)<br />

❑ The column(s) that the constraint applies to<br />

Chapter 6: Constraints<br />

159

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

Saved successfully!

Ooh no, something went wrong!