Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

cdn.s3techtraining.com
from cdn.s3techtraining.com More from this publisher
17.06.2013 Views

Chapter 6: Constraints FOREIGN KEY Constraints Foreign keys are both a method of ensuring data integrity and a manifestation of the relationships between tables. When you add a foreign key to a table, you are creating a dependency between the table for which you define the foreign key (the referencing table) and the table your foreign key references (the referenced table). After adding a foreign key, any record you insert into the referencing table must either have a matching record in the referenced column(s) of the referenced table, or the value of the foreign key column(s) must be set to NULL. This can be a little confusing, so let’s do it by example. When I say that a value must be “set to NULL,” I’m referring to how the actual INSERT statement looks. As we’ll learn in a moment, the data may actually look slightly different once it gets in the table, depending on what options you’ve set in your FOREIGN KEY declaration. Let’s create another table in our Accounting database called Orders. One thing you’ll notice in this CRE- ATE script is that we’re going to use both a primary key and a foreign key. A primary key, as we will see as we continue through the design, is a critical part of a table. Our foreign key is added to the script in almost exactly the same way as our primary key was, except that we must say what we are referencing. The syntax goes on the column or columns that we are placing our FOREIGN KEY constraint on, and looks something like this: FOREIGN KEY REFERENCES () [ON DELETE {CASCADE|NO ACTION|SET NULL|SET DEFAULT}] [ON UPDATE {CASCADE|NO ACTION|SET NULL|SET DEFAULT}] Try It Out Creating a Table with a Foreign Key 160 For the moment, we’re going to ignore the ON clause. That leaves us, for our Orders table, with a script that looks something like this: USE Accounting CREATE TABLE Orders ( OrderID int IDENTITY NOT NULL PRIMARY KEY, CustomerNo int NOT NULL FOREIGN KEY REFERENCES Customers(CustomerNo), OrderDate date NOT NULL, EmployeeID int NOT NULL ); Note that the actual column being referenced must have either a PRIMARY KEY or a UNIQUE constraint defined on it (we’ll discuss UNIQUE constraints later in the chapter). It’s also worth noting that primary and foreign keys can exist on the same column. You can see an example of this in the AdventureWorks2008 database with the SalesOrderDetail table. The primary key is composed of both the SalesOrderID and SalesOrderDetailID columns — the former is also the foreign key and references the SalesOrderHeader table. We’ll actually create a table later in the chapter that has a column that is both a primary key and a foreign key.

How It Works Once you have successfully run the preceding code, run sp_help, and you should see your new constraint reported under the constraints section of the sp_help information. If you want to get even more to the point, you can run sp_helpconstraint. The syntax is easy: EXEC sp_helpconstraint Run sp_helpconstraint on our new Orders table, and you’ll get information back giving you the names, criteria, and status for all the constraints on the table. At this point, our Orders table has one FOREIGN KEY constraint and one PRIMARY KEY constraint. Our new foreign key has been referenced in the physical definition of our table, and is now an integral part of our table. As we discussed in Chapter 1, the database is in charge of its own integrity. Our foreign key enforces one constraint on our data and makes sure our database integrity remains intact. Unlike primary keys, foreign keys are not limited to just one per table. We can have between 0 and 253 foreign keys in each table. The only limitation is that a given column can reference only one foreign key. However, you can have more than one column participate in a single foreign key. A given column that is the target of a reference by a foreign key can also be referenced by many tables. Adding a Foreign Key to an Existing Table Just like with primary keys, or any constraint for that matter, there are situations where we want to add our foreign key to a table that already exists. This process is similar to creating a primary key. Try It Out Adding a Foreign Key to an Existing Table Let’s add another foreign key to our Orders table to restrict the EmployeeID field (which is intended to have the ID of the employee who entered the order) to valid employees as defined in the Employees table. To do this, we need to be able to uniquely identify a target record in the referenced table. As I’ve already mentioned, you can do this by referencing either a primary key or a column with a UNIQUE constraint. In this case, we’ll make use of the existing primary key that we placed on the Employees table earlier in the chapter: ALTER TABLE Orders ADD CONSTRAINT FK_EmployeeCreatesOrder FOREIGN KEY (EmployeeID) REFERENCES Employees(EmployeeID); Chapter 6: Constraints When you run sp_helpconstraint on this table, the word “clustered” will appear right after the reporting of the PRIMARY KEY. This just means it has a clustered index. We will explore the meaning of this further in Chapter 9. Now execute sp_helpconstraint again against the Orders table, and you’ll see that our new constraint has been added. 161

Chapter 6: Constraints<br />

FOREIGN KEY Constraints<br />

Foreign keys are both a method of ensuring data integrity and a manifestation of the relationships between<br />

tables. When you add a foreign key to a table, you are creating a dependency between the table for which<br />

you define the foreign key (the referencing table) and the table your foreign key references (the referenced<br />

table). After adding a foreign key, any record you insert into the referencing table must either have a<br />

matching record in the referenced column(s) of the referenced table, or the value of the foreign key column(s)<br />

must be set to NULL. This can be a little confusing, so let’s do it by example.<br />

When I say that a value must be “set to NULL,” I’m referring to how the actual INSERT statement<br />

looks. As we’ll learn in a moment, the data may actually look slightly different once it gets in the table,<br />

depending on what options you’ve set in your FOREIGN KEY declaration.<br />

Let’s create another table in our Accounting database called Orders. One thing you’ll notice in this CRE-<br />

ATE script is that we’re going to use both a primary key and a foreign key. A primary key, as we will see<br />

as we continue through the design, is a critical part of a table. Our foreign key is added to the script in<br />

almost exactly the same way as our primary key was, except that we must say what we are referencing.<br />

The syntax goes on the column or columns that we are placing our FOREIGN KEY constraint on, and<br />

looks something like this:<br />

<br />

FOREIGN KEY REFERENCES ()<br />

[ON DELETE {CASCADE|NO ACTION|SET NULL|SET DEFAULT}]<br />

[ON UPDATE {CASCADE|NO ACTION|SET NULL|SET DEFAULT}]<br />

Try It Out Creating a Table with a Foreign Key<br />

160<br />

For the moment, we’re going to ignore the ON clause. That leaves us, for our Orders table, with a script<br />

that looks something like this:<br />

USE Accounting<br />

CREATE TABLE Orders<br />

(<br />

OrderID int IDENTITY NOT NULL<br />

PRIMARY KEY,<br />

CustomerNo int NOT NULL<br />

FOREIGN KEY REFERENCES Customers(CustomerNo),<br />

OrderDate date NOT NULL,<br />

EmployeeID int NOT NULL<br />

);<br />

Note that the actual column being referenced must have either a PRIMARY KEY or a UNIQUE constraint<br />

defined on it (we’ll discuss UNIQUE constraints later in the chapter).<br />

It’s also worth noting that primary and foreign keys can exist on the same column. You can see an<br />

example of this in the AdventureWorks<strong>2008</strong> database with the SalesOrderDetail table. The primary<br />

key is composed of both the SalesOrderID and SalesOrderDetailID columns — the former is<br />

also the foreign key and references the SalesOrderHeader table. We’ll actually create a table later in<br />

the chapter that has a column that is both a primary key and a foreign key.

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

Saved successfully!

Ooh no, something went wrong!