Beginning Microsoft SQL Server 2008 ... - S3 Tech Training
Beginning Microsoft SQL Server 2008 ... - S3 Tech Training Beginning Microsoft SQL Server 2008 ... - S3 Tech Training
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
- Page 148 and 149: Chapter 4: JOINs 110 CREATE TABLE U
- Page 150 and 151: Chapter 4: JOINs There are two diff
- Page 152 and 153: Chapter 5: Creating and Altering Ta
- Page 154 and 155: Chapter 5: Creating and Altering Ta
- Page 156 and 157: Chapter 5: Creating and Altering Ta
- Page 158 and 159: Chapter 5: Creating and Altering Ta
- Page 160 and 161: Chapter 5: Creating and Altering Ta
- Page 162 and 163: Chapter 5: Creating and Altering Ta
- Page 164 and 165: Chapter 5: Creating and Altering Ta
- Page 166 and 167: Chapter 5: Creating and Altering Ta
- Page 168 and 169: Chapter 5: Creating and Altering Ta
- Page 170 and 171: Chapter 5: Creating and Altering Ta
- Page 172 and 173: Chapter 5: Creating and Altering Ta
- Page 174 and 175: Chapter 5: Creating and Altering Ta
- Page 176 and 177: Chapter 5: Creating and Altering Ta
- Page 178 and 179: Chapter 5: Creating and Altering Ta
- Page 180 and 181: Chapter 5: Creating and Altering Ta
- Page 182 and 183: Chapter 5: Creating and Altering Ta
- Page 184 and 185: Chapter 5: Creating and Altering Ta
- Page 186 and 187: Chapter 5: Creating and Altering Ta
- Page 188 and 189: Chapter 5: Creating and Altering Ta
- Page 190 and 191: Chapter 5: Creating and Altering Ta
- Page 192 and 193: Chapter 6: Constraints At a more sp
- Page 194 and 195: Chapter 6: Constraints We can then
- Page 196 and 197: Chapter 6: Constraints A table can
- Page 200 and 201: Chapter 6: Constraints How It Works
- Page 202 and 203: Chapter 6: Constraints Cascading Ac
- Page 204 and 205: Chapter 6: Constraints 166 This is
- Page 206 and 207: Chapter 6: Constraints 168 FROM Ord
- Page 208 and 209: Chapter 6: Constraints 170 Let’s
- Page 210 and 211: Chapter 6: Constraints CHECK Constr
- Page 212 and 213: Chapter 6: Constraints Defining a D
- Page 214 and 215: Chapter 6: Constraints Ignoring Bad
- Page 216 and 217: Chapter 6: Constraints Try running
- Page 218 and 219: Chapter 6: Constraints Rules and De
- Page 220 and 221: Chapter 6: Constraints Dropping Rul
- Page 222 and 223: Chapter 6: Constraints 184 Restrict
- Page 225 and 226: 7 Adding More to Our Queries When I
- Page 227 and 228: Building a Nested Subquery A nested
- Page 229 and 230: While this works just fine, queries
- Page 231 and 232: We’ll go back to the AdventureWor
- Page 233 and 234: ❑ Aliases are used in both querie
- Page 235 and 236: Now let’s see this at work in our
- Page 237 and 238: So let’s take this now and apply
- Page 239 and 240: This join-based syntax, for example
- Page 241 and 242: IF NOT EXISTS (SELECT ‘True’ FR
- Page 243 and 244: The conversions can actually get a
- Page 245 and 246: there are no other roll up records
- Page 247 and 248: GROUP BY soh.OrderDate, sod.Product
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.