Implementing
Data Integrity
Vu Tuyet Trinh
Hanoi University of Technology
1
MicrosoftMicrosoft
Data Integrity
Defining the quality of the data in the database.
Types:
Domain Integrity
(columns)
Entity Integrity (rows)
Referential
Integrity
(between tables)
User-defined
integrity
MicrosoftMicrosoft
Enforcing Data Integrity
Declarative data integrity
Defined in object definitions
Enforced automatically SQL Server by using constraints,
defaults, and rules
Procedural data integrity
Defined in script
Enforced by executing scripts, triggers and stored procedures
MicrosoftMicrosoft
Outline
√
Data Integrity
Enforcing Data Integrity
Types of Constraints
Defining Constraints
Disabling Constraints
Using Defaults and Rules
Deciding enforcement method to use
MicrosoftMicrosoft
Types of Constraints
PRIMARY KEY constraints
UNIQUE constraints
FOREIGN KEY constraints
CHECK constraints
DEFAULT constraints
Cascading referential integrity
MicrosoftMicrosoft
PRIMARY KEY Constraints
Only one PRIMARY KEY constraint per table
Unique values
Not allowed NULL values
Enforced with unique index
USE Northwind
ALTER TABLE dbo.Customers
ADD CONSTRAINT PK_Customers
PRIMARY KEY NONCLUSTERED (CustomerID)
MicrosoftMicrosoft
UNIQUE Constraints
Defined with one or more columns
Allowing one null value
Allowing multiple UNIQUE constraints on a table
Enforced with a unique Index
USE Northwind
ALTER TABLE dbo.Suppliers
ADD CONSTRAINT U_CompanyName
UNIQUE NONCLUSTERED (CompanyName)
MicrosoftMicrosoft
FOREIGN KEY Constraints
Single or multi-column referential integrity
Must reference a PRIMARY KEY or UNIQUE constraint
Must have SELECT or REFERENCES permissions on
referenced tables
Use only REFERENCES clause within same table
USE Northwind
ALTER TABLE dbo.Orders
ADD CONSTRAINT FK_Orders_Customers
FOREIGN KEY (CustomerID)
REFERENCES dbo.Customers(CustomerID)