Definition defaults are great for affecting just a single column like you did here,but because state is a user-defined datatype that can be used in any of your tables inthe Sales databas
Trang 14 To see the new record, choose Query ➣ New Query.
5 Enter and execute the following code:
SELECT * FROM customers
6 Notice that the record now exists with a custid of 1 (that is because of the
iden-tity property discussed earlier, which automatically added the number for you)
7 To test the check constraint by adding characters in the zip field, choose Query ➣
New Query
8 In the query window, enter the following code and note the letters in the zip
code field:
USE salesINSERT customersVALUES (‘John’,’Smith’,’817 3rd’,’Chicago’,’IL’,’AAB1C’,’8015551212’)
9 Notice in the results pane that the query violated a constraint and so failed.
Trang 2Another tool at your disposal for protecting against incorrect data is the rule Rules
work just like constraints, validating user data before it is allowed in the table Theonly difference between rules and constraints is that rules can be bound to a user-defined datatype, and constraints cannot Binding a rule will attach the rule to thedatatype so that everywhere you use that datatype, the rule is already in place,whereas a constraint would need to be specifically applied to the column every timeyou used it Let’s generate a rule for your state datatype so you can see how it’s done:
1 Open Enterprise Manager and expand your server, then databases, then Sales.
2 Under Sales, select Rules.
3 From the Action menu, select New Rule
4 To create a rule that will accept only 5 of the 50 state abbreviations, type State
in the Name box and enter the following in the Text box (feel free to add yourown state here if you like):
Trang 35 Click OK to create the rule.
6 Once back at Enterprise Manager, double-click the state rule to open its properties.
7 Click the Bind UDTs button to bind the new rule to the state datatype.
8 Check the Bind box next to State to bind the rule, and click OK Note that you
can also bind this to a column in a table, just like a constraint
Trang 4Now that the state rule is bound to the state datatype, every time you use the statedatatype, it will have the rule in place already In your case, every time you use thestate datatype on a column, it will allow only one of the five states in the list you cre-ated for the rule.
It is easy to see how the check constraint can be a powerful ally against enteringwrong data—all you need to do is figure out what data belongs in your column andcreate a constraint instructing SQL Server not to accept anything else Check con-straints serve no purpose if your users simply forget to enter data in a column alto-gether, though—that is what default constraints are for
Using Default Constraints
Default constraints are used to fill in fields that the users leave blank by not including
them in the INSERT or UPDATE statement that they used to add or modify a record
There are two types of defaults: object and definition Object defaults are defined when you create your table and affect only the column on which they are defined Defini-
tion defaults are created separately from tables and are designed to be bound to a
user-defined datatype (just like the rule we discussed earlier) Either type of default can be
a big time-saver in a data entry department if you use the default right
For example, suppose that most of your clientele live in California and that yourdata entry people must type CA for every new customer they enter That may notseem like much work, but if you have a sizable customer base, that can add up to a lot
of typing By using a default constraint, however, your users can leave the state fieldintentionally blank, and SQL Server will fill it in for you To demonstrate the capabili-ties of the default constraint, let’s create a definition default on the customers table:
1 Open Enterprise Manager and expand your server, then databases, then the
Sales database
2 Click the Tables icon under Databases.
3 Right-click the customers table and select Design Table.
4 Click State In the bottom half of the screen, in the Default Value column,
type 'CA' (with the single quotes) Note that SQL Server will place this inside
Trang 55 Click the Save button and exit the table designer screen.
6 To test the default, open Query Analyzer by selecting it from the Tools menu in
Enterprise Manager
7 Enter and execute the following code:
USE salesINSERT customers (fname, lname, address, city, zip, phone)VALUES (‘Tom’,’Smith’,’609 Georgia’,’Fresno’,’33405’,’5105551212’)
8 To verify that CA was entered into the state field, select New Query from the
Query menu
9 Enter and execute the following code:
SELECT * FROM customers
10 Notice that the Tom Smith record has CA in the state field, as shown in the
graphic below
Trang 6Definition defaults are great for affecting just a single column like you did here,but because state is a user-defined datatype that can be used in any of your tables inthe Sales database, it would make more sense to have the default bound to thedatatype so that you don’t need to rewrite it every time you use the datatype That iswhat object defaults are for—binding to a datatype Let’s create an object default thatwill fill in the state field with CA if the user forgets:
1 Open Enterprise Manager and expand your server, then databases, then the
Sales database
2 Under Sales, select Defaults From the Action menu, select New Default.
3 In the Name field, type StateOD.
4 In the Value field, enter 'CA' (with the single quotes).
Trang 75 Click OK to create the default.
6 Once back at Enterprise Manager, double-click the new default to bring up its
properties Click the Bind UDTs button to bind the default to a user-defineddatatype
7 Check the Bind box next to State to bind the default to the state datatype.
Now that the StateOD default is bound to the state datatype, every time you create
a field with the state datatype, the field will have a default in place that will cally fill the field with a value of CA if the user doesn’t enter a value
automati-That is all there is to enforcing domain integrity—controlling what your users canenter into your fields You can use check constraints to force your users to enter theproper data, and default constraints will fill in any data that your users might forget.However, there are still two more types of integrity to enforce Next we will see how
to keep users from entering duplicate records by enforcing entity integrity
Enforcing Entity Integrity
Ensuring that each of the records in your tables is unique in some way and that no
record is accidentally duplicated is referred to as enforcing entity integrity Why do you
need to be sure that there are no duplicate records in your tables? Imagine whatwould happen if a customer were accidentally entered twice in your customers table,thus duplicating the data You would have one customer with two different IDs, mak-ing it very difficult to decide which one to bill for orders Or, worse yet, suppose thatsomeone had accidentally entered two customers with the same ID This could causebig problems when making sales or generating reports, because you would not knowwhich customer actually bought what—they would both show up as the same customer
Trang 8Such a mess as this can be avoided by enforcing entity integrity There are two ways
to enforce entity integrity—the first is with a primary key
Using Primary Keys
A primary key is used to ensure that each of the records in your table is unique in some way It does this by creating a special type of index called a unique index An index is
ordinarily used to speed up access to data by reading all of the values in a column andkeeping an organized list of where the record that contains that value is located in thetable A unique index not only generates that list, but it does not allow duplicate val-ues to be stored in the index If a user tries to enter a duplicate value in the indexedfield, the unique index will return an error, and the data modification will fail
Suppose, for instance, that you have defined the custid field in the customers table
as a primary key and that you have a customer with id 1 already in the table If one ofyour users were to try to create another customer with id 1, they would receive anerror, and the update would be rejected because custid 1 is already listed in the pri-mary key’s unique index Of course this is just for example, because your custid fieldhas the identity property set, which automatically assigns a number with each newrecord inserted and will not allow you to enter a number of your own design
NOTE When a column can be used as a unique identifier for a row (such as an identitycolumn), it is referred to as a surrogate or candidate key.
The primary key should be made of a column (or columns) that contains uniquevalues This makes an identity column the perfect candidate for becoming a primarykey, because the values contained therein are unique by definition If you do not have
an identity column, make sure to choose a column, or combination of columns, inwhich each value is unique Since you have an identity column in the customerstable, let’s use it to create a primary key:
1 Open Enterprise Manager by selecting it from the SQL Server 2000 group in
Pro-grams on your Start menu, expand your server, then expand databases
2 Expand the Sales database and click Tables.
3 Right-click the customers table and select Design Table.
4 In the table designer screen, right-click CustID under Column Name and select
Set Primary Key
5 Notice that just to the left of the CustID field, there is a small key icon denoting
Trang 96 When you click the Save icon on the toolbar, SQL Server will create the unique
index, which ensures that no duplicate values can be entered in the custid field
7 Close the table designer.
TIP When a column has mostly unique values, it is said to have high selectivity When a column has several duplicate values, it is said to have low selectivity Therefore the primary
key field must have high selectivity (entirely unique values)
That procedure was fairly simple, but suppose that you need to maintain entityintegrity separately on more than one column Perhaps you have an employees tablewith an employeeid field that has been set as the primary key, but you also have aSocial Security number field on which you need to enforce entity integrity Becauseyou can have only one primary key per table, you would need to create a unique con-straint to enforce such entity integrity
Trang 10Using Unique Constraints
There are two major differences between primary key constraints and unique straints The first is that primary keys are used with foreign keys to enforce referentialintegrity (which we will discuss a little later in this chapter), and unique keys are not
con-The second difference is that unique constraints allow null (blank) values to beinserted in the field, whereas primary keys do not allow null values Aside from that,they serve the same purpose—to ensure that unique data is inserted in a field
You should use a unique constraint when you need to ensure that no duplicate ues can be added to a field that is not part of your primary key A good example of afield that might require a unique constraint is a Social Security number field, becauseall of the values contained therein need to be unique, yet there would most likely be aseparate employee ID field that would be used as the primary key Because you don’treally have a perfect candidate for a unique constraint in your tables, you will come asclose as you can by creating a unique constraint on the Phone field:
val-1 While still in Enterprise Manager, right-click the customers table and select
Design Table
2 Right-click the Phone field and select Indexes/Keys.
3 Click the New button.
4 Under Column Name, select Phone.
5 In the Order box, select Ascending—this orders the index from lowest to highest
values (i.e., one at the top and nine at the bottom, or A at the top and Z at thebottom)
6 In the Index Name box, type Unique_Phone.
7 Check the Create UNIQUE box.
8 Under Create UNIQUE, click the Constraint radio button.
Trang 119 Click the Close button.
10 Click the Save icon on the toolbar.
11 Close the table designer screen.
Now you can test the unique constraint by trying to add some duplicate phonenumbers through Query Analyzer using some INSERT statements:
1 Open Query Analyzer by selecting it from the Tools menu in Enterprise Manager.
2 Enter and execute the following code to add a new record to the customers
table:
USE salesINSERT customersVALUES (‘Shane’,’Travis’,’806 Star’,’Phoenix’,’AZ’,’85202’,’6021112222’)
3 Try entering another customer with the same phone number by entering and
executing the following:
USE salesINSERT customers
Trang 12VALUES (‘Janet’,’McBroom’,’5403Western’,’Tempe’,’AZ’,’85103’,’6021112222’)
4 Notice that this failed, with a message that the UNIQUE constraint had been
violated by the duplicate phone number
You now know how to protect the data that is entered in your tables by enforcingdomain and entity integrity, but there is still one more area of integrity to consider
You need to know how to protect related data that is stored in separate tables byenforcing referential integrity
Enforcing Referential Integrity
You have three tables in your Sales database right now: one for customer data, onefor product data, and one for order data Each of these tables contains data that isaffected by what is stored in one of your other tables For instance, the orders table
is affected by the customers table in that you should not create an order for a tomer that does not exist in your customers table The orders table is also affected
cus-by the products table in that you do not want to create an order for a product thatdoes not exist If you want to make sure that a customer exists in your customerstable before you sell them something, or if you do not want to sell nonexistent
products, you need to enforce referential integrity. Digg
Trang 13Enforcing referential integrity does just what its name implies: Data in one tablethat refers to data in another table is protected from improper updating In SQL
Server terminology, the process of enforcing referential integrity is called declarative
referential integrity (DRI), and it is accomplished by linking the primary key of one of
your tables to a foreign key in another table Let’s see what foreign keys do and how
to create them
Using Foreign Keys
A foreign key is used in combination with a primary key to relate two tables on a
com-mon column You could, for example, relate the orders table and the customers table
on the custid column that they both have in common If you use the custid field inthe customers table as the primary key (which you already have), you can use thecustid field in the orders table as the foreign key that relates the two tables Now,unless you enable cascading referential integrity (which we’ll discuss shortly), youwould not be able to add a record to the orders table if there is no matching record inthe customers table Not only that—you would not be able to delete a record in thecustomers table if there are matching records in the orders table, because you don’twant to have orders out there with no customer information Before you see how thisworks, it is probably best to show you exactly what happens without referentialintegrity being enforced:
1 If you are still in Enterprise Manager, open Query Analyzer by selecting it from
the Tools menu
2 To insert a record with a customer ID, product ID, quantity, and current date (as
reported by the GETDATE() function) in the orders table, enter and execute thefollowing code:
USE salesINSERT ordersVALUES (999,5,57,getdate())
3 Notice in the preceding step that you were successful even though there is no
customer in the customers table with an ID of 999
4 To remove the erroneous records, enter and execute the following code (note
that this is a potentially dangerous command, because it deletes all records from
a table):
truncate table orders
Now that you have proven that you can enter an order for a nonexistent customer,you need to protect your database against that To do this, you will create a foreignkey on the custid field of the orders table that relates to the custid field of the customers
Trang 14table (which is the primary key of the customers table) With this relationship inplace, your data will be protected across your tables Let’s create that relationship:
1 Open Enterprise Manager, expand your server, expand databases, then click
Tables under the Sales database
2 Right-click the orders table and select Design Table
3 Right-click the CustID field and select Relationships.
4 Click the New button to create a new relationship.
5 In the Primary Key drop-down list, select Customers.
6 In the Foreign Key drop-down list, select Orders.
7 In the table just below the Primary Key drop-down list, in the left side of the
first line, select CustID as the primary-key column
8 In the right side of the same table, just under the foreign-key drop-down box,
select CustID as the foreign-key column
9 In the Name box, type FK_Customers_Orders.
10 Leave the rest as defaults and click Close to create the relationship.
11 Click Yes when asked to save tables to the diagram (discussed later).
Trang 15We’ll test that new relationship in just a moment—you are probably wonderingwhat those checkboxes at the bottom of the dialog box were for, though We’ll discussthe two at the very bottom of the dialog box a little later, but here are descriptions forthree of them:
Check Existing Data on Creation: The first checkbox is to instruct SQLServer to verify that all of the existing data in both tables fits the constraintparameters; if it does not, you will receive a warning instructing you to fix it
Enable Relationship for Replication: Replication is used for copyingdatabases from one server to another This option will enable the relationship
to be copied via replication to another server along with the primary- andforeign-key tables
Enable Relationship for INSERTs and UPDATEs: If you find that you
no longer need the relationship you have created, you can uncheck this box todisable it while leaving the relationship in place This way, you do not need tocompletely re-create the relationship if you find that you need it again later Now you are ready to test the new relationship Here you will try to add somerecords to the orders table that have no corresponding record in the customers table,then you will try to delete a record from the customers table that references a record
in the orders table:
1 To test the new foreign-key constraint, you will try to add the same record as in
the last set of steps in Query Analyzer:
USE salesINSERT ordersVALUES (999,5,57,getdate())
2 Notice that the addition failed because there is no customer number 999 in the
customers table
Trang 163 To make very sure that this is working, you will add a record to the orders table
that has a matching customer number by executing the following code in a newquery window:
USE sales
4 Notice that the previous code was successful because customer 1 actually exists.
5 Now that you have a matching record in the orders table, let’s try to delete
cus-tomer 1 from the cuscus-tomers table:
USE salesDELETE from customersWHERE custid = 1
Trang 17Now you can see how the records in related tables are protected from improperupdates Users cannot add a record to a foreign-key table without a correspondingrecord in the primary-key table, and primary-key records cannot be deleted if they havematching foreign-key records But wait, it gets even better: New with SQL Server 2000 issomething called cascading referential integrity.
Using Cascading Referential Integrity
You just saw that the default behavior for a relationship is to prevent the addition ordeletion of records in the related tables based on the existence of matching records Arecord in a primary key cannot be deleted if there are corresponding records in the
foreign-key table, for example This behavior can be changed, however, by using
cas-cading referential integrity.
Trang 18You probably noticed the two checkboxes just under the Enforce Relationship forINSERTs and UPDATEs checkbox in the Create Relationship dialog box Those twocheckboxes control the behavior of cascading referential integrity:
Cascade Update Related Fields: When this option is unchecked, youcannot change the value of a primary-key field if it has matching records inthe foreign-key table With this option checked, you can change the value of aprimary-key field, and the matching foreign-key records will be automaticallyupdated
Cascade Delete Related Records: With this option unchecked, you cannotdelete a record from the primary-key table if there are corresponding foreign-keyrecords With this option checked, you can delete a record in the primary-keytable, and all matching foreign-key records will be removed automatically
Let’s give this a try to demonstrate how it works First, you need to disable theidentity property of the custid field in the customers table, because you cannot manu-ally assign a value to a field with an identity property assigned to it, and you need to
be able to do just that for a full test of cascading referential integrity Once thatprocess is finished, you will set both cascade options on your relationship and test thecascade capabilities:
1 Open Enterprise Manager, expand your server, expand databases, then click
Tables under the Sales database
2 Right-click the customers table and select Design Table.
3 Click the CustID field and, in the bottom half of the screen, set the identity
property to No
4 Click the Save button and click Yes when asked whether you want to save
changes to the diagram
5 Close the table designer and get back to Enterprise Manager.
6 Right-click the orders table and select Design Table
7 Right-click the CustID field and select Relationships.
8 At the bottom of the dialog box, check both of the options for cascading.
Trang 191 Open Query Analyzer by selecting it from the Tools menu.
2 First you will verify the existing records in the customers and orders tables by
entering and executing the following code (note that both lines are executed atthe same time) You should see three customers and one order for custid 1 in theresult sets:
select * from customersselect * from orders
Trang 203 To test the cascaded update feature, enter and execute the following code:
UPDATE customersSET custid = 5WHERE custid = 1
4 Enter and execute the same code from step 2 again Notice that custid 1 has
been changed to 5 in the customers and orders tables
Trang 215 To test the cascaded delete feature, enter and execute the following code to
delete customer 5:
DELETE from customersWHERE custid = 5
6 Enter and execute the same code from step 2 again Notice that the customer 5
record has been deleted from the customers table as well as the matchingrecords from the orders table
You now know how to declare referential integrity that both denies and cascadesupdates In fact, you know how to restrict any data that a user may try to enter inyour tables It would be really nice, though, if you could make this even easier Say nomore—database diagrams are designed to do just that
Using Database Diagrams
Everything you have done up to this point has been graphical, meaning that you havebeen able to use Enterprise Manager to do everything rather than using Transact-SQLcode That is good, but it could be better Remember the foreign-key relationship thatyou created a few pages back? It would have been easier if you could’ve actually seen the
Trang 22tables and maybe used drag and drop to create the relationship You can use databasediagrams to do this and a great deal more In fact, quite a few of your database manage-ment activities can be performed using a database diagram.
A database diagram is a picture of the database Specifically, it is a graphic depiction
of the schema (whole or partial) of the database, showing the tables and columns,and the relationships between them Let’s create a database diagram here to see what
it is capable of:
1 Open Enterprise Manager, expand your server, expand databases, then expand
the Sales database
2 Click Diagrams under the Sales database.
3 Right-click Diagrams and select New Diagram to launch the Create Database
Diagram Wizard Click the Next button on the first screen
4 On the second screen, add Customers, Orders, and Products to the diagram by
selecting each one and clicking the Add button Then click Next
Trang 235 Click Finish to create the diagram.
6 Notice that the diagram has now been created and is being displayed for
you Notice the foreign-key relationship you created earlier as well as the primary key on the customers table
Trang 24N OTE A database diagram is a graphic representation of the database schema Theschema is the structure of the database, and it describes things such as the names ofcolumns, datatypes, table relationships, and all other components of the database structure.
Now that you have successfully created a database diagram for the Sales database,let’s see what the database diagram can do In this next set of steps, you are going tocreate a primary key on the products table and then relate the products and orderstables, all using the database diagram:
1 To create a primary key on the products table, right-click the ProdID column
and select Set Primary Key (you may need to enlarge the graphic by clicking themagnifying glass icon on the toolbar to see the column names) Notice the littlekey icon just to the left of the column name
Trang 252 To create a foreign-key relationship between the products table and the orders
table, hover your mouse pointer over the gray box to the left of the ProdID umn in the orders table
col-3 Click and drag the mouse to the products table, and drop the icon on the ProdID
column
4 Accept the defaults in the Create Relationship dialog box by clicking OK.
5 Notice the gray line denoting a relationship between the products and orders
tables Close the diagram by clicking the X in the upper-right corner of thescreen
6 When asked to save the diagram, click Yes.
7 Save the diagram as Sales and click OK.
8 Click Yes when asked to save the changes made to your tables.
Now you have a fully functional database diagram that can be used to modify thestructure of your tables and create relationships between them Such diagrams can bevery helpful and timesaving when you get to know them