|
Establishing a Relationship |
|
As mentioned already, a relational database is one in which
information flows from one table to another. To prepare the tables for this, you
create primary and foreign keys, which we have done so far. Once the tables are
ready, you can link them, which is referred to as creating a relationship
between two tables.
If you didn't create a foreign key with SQL code, you can
create it when establishing a relationship between two tables.
To create a relationship between two tables
- Open the child table in the design view
- Right-click (anywhere in) the table and click Relationships...
If the (necessary) foreign key doesn't exist, click Add and specify its name
under Identity) in the right side.
- Under Selected Relationships, click the foreign key that will hold the
relationship
- In the right side, expand Tables And Columns Specification
- Click its ellipsis button

- In the Primary Key Table combo box, select the parent table that
holds the primary data
- Under the parent table, click and select its primary key column
- Under Foreign Key Table, make sure the name of the current table is
set.
Under the name of the child table, click and select the name of the
foreign key column. Here is an example:

- Click OK.
When a relationship has been created, it would show in the Tables And
Column Specification section:

- In the same way, you can create other relationships by clicking Add
and configuring the link.
Once you have finished, click Close
|
Practical
Learning: Creating Relationships
|
|
- To complete our database with its tables, their primary keys, their
foreign keys, and some data in the tables, change the code in the
query window as follows:
-- =============================================
-- Database: YugoNationalBank
-- Author: FunctionX
-- Date Created: Monday 09 April 2007
-- =============================================
USE master
GO
-- Drop the database if it already exists
IF EXISTS (
SELECT name
FROM sys.databases
WHERE name = N'YugoNationalBank'
)
DROP DATABASE YugoNationalBank
GO
CREATE DATABASE YugoNationalBank
GO
-- =========================================
-- Database: YugoNationalBank
-- Table: Locations
-- =========================================
USE YugoNationalBank
GO
IF OBJECT_ID(N'dbo.Locations', N'U') IS NOT NULL
DROP TABLE dbo.Locations
GO
CREATE TABLE Locations
(
LocationID int Identity(1,1) NOT NULL,
LocationCode nvarchar(10) NOT NULL,
Address nvarchar(120),
City nvarchar(50),
State nvarchar(50),
Notes text NULL,
CONSTRAINT PK_Locations PRIMARY KEY (LocationID)
);
GO
-- =========================================
-- Database: YugoNationalBank
-- Table: AccountTypes
-- =========================================
USE YugoNationalBank
GO
IF OBJECT_ID(N'dbo.AccountTypes', N'U') IS NOT NULL
DROP TABLE dbo.AccountTypes
GO
CREATE TABLE AccountTypes
(
AccountTypeID int Identity(1,1) NOT NULL,
AccountType nvarchar(40) NOT NULL,
Notes text NULL,
CONSTRAINT PK_AccountTypes PRIMARY KEY (AccountTypeID)
);
GO
-- =========================================
-- Database: YugoNationalBank
-- Table: Employees
-- =========================================
IF OBJECT_ID(N'dbo.Employees', N'U') IS NOT NULL
DROP TABLE dbo.Employees
GO
CREATE TABLE Employees
(
EmployeeID int identity(1,1) NOT NULL,
EmployeeNumber char(6),
FirstName nvarchar(32),
LastName nvarchar(32) NOT NULL,
Title nvarchar(50),
CanCreateNewAccount bit,
HourlySalary smallmoney,
EmailAddress nvarchar(100),
Username nvarchar(20),
Password nvarchar(20),
Notes text,
CONSTRAINT PK_Employees PRIMARY KEY (EmployeeID)
);
GO
-- =========================================
-- Database: YugoNationalBank
-- Table: Customers
-- =========================================
IF OBJECT_ID(N'dbo.Customers', N'U') IS NOT NULL
DROP TABLE dbo.Customers
GO
CREATE TABLE Customers
(
CustomerID int Identity(1,1) NOT NULL,
DateCreated date,
AccountNumber nvarchar(20),
AccountTypeID int Constraint FK_TypeOfAccount
References AccountTypes(AccountTypeID),
CustomerName nvarchar(50) NOT NULL,
DateUpdated date,
Notes text,
CONSTRAINT PK_Customers PRIMARY KEY (CustomerID)
);
GO
-- =========================================
-- Database: YugoNationalBank
-- Table: ChargeReasons
-- =========================================
IF OBJECT_ID(N'dbo.ChargeReasons', N'U') IS NOT NULL
DROP TABLE dbo.ChargeReasons
GO
-- =========================================
-- Database: YugoNationalBank
-- Table: Deposits
-- =========================================
IF OBJECT_ID(N'dbo.Deposits', N'U') IS NOT NULL
DROP TABLE dbo.Deposits
GO
CREATE TABLE Deposits
(
DepositID int identity(1, 1) NOT NULL,
LocationID int Constraint FK_DepositLocation
References Locations(LocationID) NOT NULL,
EmployeeID int Constraint FK_Clerk
References Employees(EmployeeID),
CustomerID int Constraint FK_Depositor
References Customers(CustomerID) NOT NULL,
DepositDate date NOT NULL,
DepositAmount smallmoney NOT NULL,
Notes text,
CONSTRAINT PK_Deposits PRIMARY KEY (DepositID)
);
GO
-- =========================================
-- Database: YugoNationalBank
-- Table: Withdrawals
-- =========================================
IF OBJECT_ID(N'dbo.Withdrawals', N'U') IS NOT NULL
DROP TABLE dbo.Withdrawals
GO
CREATE TABLE Withdrawals
(
WithdrawalID int identity(1, 1) NOT NULL,
LocationID int Constraint FK_WithdrawlLocation
References Locations(LocationID) NOT NULL,
EmployeeID int Constraint FK_ProcessedBy
References Employees(EmployeeID),
CustomerID int Constraint FK_CustomerAccount
References Customers(CustomerID) NOT NULL,
WithdrawalDate date NOT NULL,
WithdrawalAmount smallmoney NOT NULL,
WithdrawalSuccessful bit NOT NULL,
Notes text,
CONSTRAINT PK_Withdrawas PRIMARY KEY (WithdrawalID)
);
-- =========================================
-- Database: YugoNationalBank
-- Table: CheckCashing
-- =========================================
IF OBJECT_ID(N'dbo.CheckCashing', N'U') IS NOT NULL
DROP TABLE dbo.CheckCashing
GO
CREATE TABLE CheckCashing
(
CheckCashingID int identity(1, 1) NOT NULL,
LocationID int Constraint FK_BranchLocations
References Locations(LocationID) NOT NULL,
EmployeeID int Constraint FK_Employees
References Employees(EmployeeID),
CustomerID int Constraint FK_Customers
References Customers(CustomerID) NOT NULL,
CheckCashingDate date NOT NULL,
CheckCashingAmount smallmoney NOT NULL,
CheckCashingSuccessful bit NOT NULL,
Notes text,
CONSTRAINT PK_CheckCashing PRIMARY KEY(CheckCashingID)
);
GO
|
- Press F5 to execute the statement
A diagram is a window that visually displays the
relationships among tables of a database. To create a diagram:
- In the Object Explorer, in the database node, you can click Database
Diagrams
- A dialog box will inform you that this database doesn't have a
diagram. Read the message and click Yes
- Right-click Database Diagrams and click New Database Diagram
- In the Add Table dialog box, click each table and click the Add.
Alternatively, you can double-click a table to add it
- In the Add Table dialog box, you can click
Close.
On the toolbar, you can click the Zoom button and select a larger or
smaller value.
To move a table, you can drag its title bar. Here is an example:

- To establish a relationship, you can click the gray box on the left of
any column from the parent table and drop it on any column in the
child table. A better way is to click gray box of the primary key
column from the parent table, drag that box then drop it on the
foreign key column of the child table. Here is an example:

- A Tables and Columns dialog box would come up. It would display the
column that was dragged and the column on which you dropped.
If you had selected just any column, it would show but it may not be
the one you wanted to drag; that is, it may not be the actual column
that is supposed to manage the relationship.
Regardless, under Primary Key Table, you should select the parent
table
- Under the parent table, select its primary column
- Under Foreign Table, select the foreign key column. Here is an
example:

- Once you are ready, click OK. A link would be created between the
tables

- In the same way, you can create other relationships.
When you have finished, you can save and close the database
|
Practical
Learning: Creating a Diagram
|
|
- In the Object Explorer, in the YugoNationalBank node, click Database
Diagrams
- A dialog box will inform you that this database doesn't have a
diagram:

Read the message and click Yes
- Right-click Database Diagrams and click New Database Diagram
- In the Add Table dialog box, click Customers and click the Add >
button
- Double-click CheckCashing to add it
- In the same way, add the AccountTypes , Deposits, Employees,
Locations, and Withdrawals tables
- On the Add Table dialog box, click Close.
Notice that, based on how we created the database and its objects, the
relationships have been created already:

- To save the diagram, on the Standard toolbar, click Save
- Set its name to dgmYugoNationalBank and click OK
- Close the window
On a typical database, information comes and goes. For a
bank, customers accounts are created and deleted on a regular basis.
When an account is deleted, there is concern about the transactions related to
that account. Referential integrity allows you to manage these aspects of a
database. You need to make sure that when data is deleted from a parent table, the
child tables are notified and their related records are deleted also. When
information is changed on a parent table, the related information is changed in
the child tables.
To manage referential integrity, you use the Foreign Key
Relationships dialog box. You can access it from the design view of a table or
from the diagram window.
|
Practical
Learning: Managing Referential Integrity
|
|
- In the Object Explorer, expand the Tables node under
YugoNationalBank.
Right-click dbo.Customers and click
Design
- Right-click in the table and click Relationships
- Under Selected Relationships, click FK_CustomerAccount. In the right
section, expand INSERT And UPDATE Specification
- Click Delete Rule. In its combo box, select Cascade
- Click Update Rule. In its combo box, select Cascade:

- In the same way, specify the following
| Foreign Key |
Delete Rule |
Update Rule |
| FK_ChargeReasons |
Cascade |
Cascade |
| FK_Customers |
Cascade |
Cascade |
| FK_Depositor |
Cascade |
Cascade |
| FK_TypeOfAccount |
Cascade |
Cascade |
- Click Close
- Save and close the table
- In the same way, open the Deposits table in design view
- Access its Relationships dialog box
- Access the properties of its FK_Clerk field.
Specify its Delete Rule and its Update Rule both to Cascade
- Perform the same actions for the other relationships
- Close the Relationships dialog box
- Save and close the table
When performing data entry, in some columns, even
after indicating the types of values you expect the user to provide for a
certain column, you may want to restrict a range of values that are allowed. In
the same way, you can create a rule that must be respected on a combination of
columns before the record can be created. For example, you can ask the database
engine to check that at least one of two columns received a value. For example,
on a table that holds information about customers, you can ask the database
engine to check that, for each record, either the phone number or the email
address of the customer is entered.
The ability to verify that one or more rules are respected
on a table is called a check constraint. A check constraint is a Boolean operation performed
by the SQL interpreter. The interpreter examines a value that has just been
provided for a column. If the value is appropriate:
- The constraint produces TRUE
- The value gets accepted
- The value is assigned to the column
If the value is not appropriate:
- The constraint produces FALSE
- The value gets rejected
- The value is not assigned to the column
You create a check constraint at the time you are creating a
table.
|
Visually Creating a Check Constraint |
|
To create a check constraint, when creating a table,
right-click anywhere in (even outside) the table and click Check
Constraints...

This would open the Check Constraints dialog box. From that
window, you can click Add. Because a constraint is an object, you must provide a name for it. The most important
piece of information that a check constraint should hold is the mechanism it
would use to check its values. This is provided as an expression. Therefore, to
create a constraint, you can click Expression and click its ellipsis button.
This would open the Check Constraint Expression dialog box.
To create the expression, first type the name of the column
on which the constraint will apply, followed by parentheses. In the parentheses,
use the arithmetic and/or SQL operators we studied already. Here is an example
that will check that a new value specified for the Student Number is greater
than 1000:

After creating the expression, you can click OK. If the
expression is invalid, you would receive an error and given the opportunity to
correct it.
You can create as many check constraints as you judge
necessary for your table:

After creating the check constraints, you can click OK.
|
Programmatically Creating a Check Constraint |
|
To create a check constraint in SQL, first create the
column on which the constraint will apply. Before the closing parenthesis of the table definition, use the
following formula:
CONSTRAINT name CHECK (expression)
The CONSTRAINT and the CHECK keywords are
required. As an object, make sure you provide a name for it. Inside the
parentheses that follow the CHECK operator, enter the expression that will be
applied. Here is an example that will make sure that the hourly salary specified
for an employee is greater than 12.50:
CREATE TABLE Employees
(
[Employee Number] nchar(7),
[Full Name] varchar(80),
[Hourly Salary] smallmoney,
CONSTRAINT CK_HourlySalary CHECK ([Hourly Salary] > 12.50)
);
It is important to understand that a check constraint it
neither an expression nor a function. A check constraint contains an expression
and may contain a function as part of its definition.
After creating the constraint(s) for a table, in the Object
Explorer of Microsoft SQL Server Management Studio, inside the table's node,
there is a node named Constraints and, if you expand it, you would see the name
of the constraint.
With the constraint(s) in place, during data entry, if the
user (or your code) provides an invalid value, an error would display. Here is
an example:

Instead of an expression that uses only the regular
operators, you can use a function to assist in the checking process. You can
create and use your own function or you can use one of the built-in Transact-SQL
functions.
|
Practical
Learning: Creating a Check Constraint
|
|
- In the Object Explorer, right-click the name of the server and click
Start PowerShell
- In the PowerShell window, type SQLCMD and press Enter
- To create a database and a new table that has a check
mechanism, type the following:
CREATE DATABASE GreensvilleElectricCompany;
GO
CREATE TABLE Customers
(
AccountNumber nchar(14) primary key not null,
CustomerName nvarchar(50) NOT NULL,
PhoneNumber nchar(16),
EmailAddress nvarchar(50),
CONSTRAINT CK_CustomerContact
CHECK ((PhoneNumber IS NOT NULL) OR (EmailAddress IS NOT NULL))
);
GO
|
- To add records to the new table, type the following:
INSERT INTO Customers
VALUES(N'188395805',N'Ann Zeke',N'301-128-3506',N'azeke@yahoo.jp'),
(N'806200422',N'Joan Simms',N'410-114-6820',N'jsimmson@emailct.com'),
(N'402628475',N'Peter Dorka',N'(202) 050-1629',N'pdorka@hotmail.com'),
(N'666204275',N'James Bengbiss',N'443-158-1833',N'jbango@emailct.com');
GO
|
- To try adding a new record to the table, type the following:
1> INSERT INTO Customers
2> VALUES(N'402628475',N'James Darfield',N'202-188-8742',N'');
3> GO
|
- Notice that you receive an error:
Msg 2627, Level 14, State 1, Server CENTRAL, Line 1
Violation of PRIMARY KEY constraint 'PK__Customer__BE2ACD6E51BA1E3A'. Cannot ins
ert duplicate key in object 'dbo.Customers'.
The statement has been terminated.
1>
|
- To delete the database, type:
DROP DATABASE GreensvilleElectricCompany;
GO
|
- Type exit and press Enter
- To close the PowerShell window, type exit and press Enter
|
|