Database Reference
In-Depth Information
Let's look at each of the candidates and see whether it violates a rule.
The first candidate (Model Number and Manufacturer) violates all the
rules; the data is a string, and it would be a composite key. So that leaves
us with SKU, which is perfect; it identifies the row, it's an integer, and it is
a single column.
Now that we have identified our PK, how do we go about configuring
it in SQL Server? There are several ways to make PKs, and the method you
use depends on the state of the table. First, let's see how to do it at the
same time you create the table. Here is the script to create the table, com-
plete with the PK.
CREATE TABLE Products(
sku int NOT NULL
PRIMARY KEY ,
modelnumber varchar(25) NOT NULL,
name varchar(100) NOT NULL,
manufacturer varchar(25) NOT NULL,
description varchar(255) NOT NULL,
warrantydetails varchar(500) NOT NULL,
price money NOT NULL,
weight decimal(5, 2) NOT NULL,
shippingweight decimal(5, 2) NOT NULL,
height decimal(4, 2) NOT NULL,
width decimal(4, 2) NOT NULL,
depth decimal(4, 2) NOT NULL,
isserialized bit NOT NULL,
status tinyint NOT NULL
)
You will notice the PRIMARY KEY statement following the definition of
the sku column. That statement adds a PK to the table on the sku column,
something that is simple and quick.
However, this method has one inherent problem. When SQL Server
creates a PK in the database, every PK has a name associated with it. Using
this method, we don't specify a name, so SQL Server makes one up. In this
case it was PK_Products_30242045. The name is based on the table name
and some random numbers. On the surface, this doesn't seem to be a big
problem, but what if you later need to delete the PK from this table? If you
have proper change control in your environment, then you will create a
script to drop the key and you will drop the key from a quality assurance
server first. Once tests confirm that nothing else will break when this key
Search WWH ::




Custom Search