Top Banner
SQL Server 7.0 Maintaining Referential Integrity
21
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: SQL Server 7.0 Maintaining Referential Integrity.

SQL Server 7.0

Maintaining Referential Integrity

Page 2: SQL Server 7.0 Maintaining Referential Integrity.

SQL Server is a RDBMS

• Relationships between entities in the data model.

• Entities are implemented as Tables.

• A mechanism ensures that Referential Integrity is not violated.

Page 3: SQL Server 7.0 Maintaining Referential Integrity.

Mechanisms to enforce Referential Integrity, Data Integrity

• Data integrity is enforced by constraints, triggers, rules, and defaults.

• We will focus on constraints and triggers.

• Constraints are:– Simple.

– Proactive.

– Query optimizer uses them.

• Triggers:– Complex logic.

– Checking data in other tables/cascade changes.

– Reactive / Incur more overhead.

Page 4: SQL Server 7.0 Maintaining Referential Integrity.

Entity Integrity

• PRIMARY KEY constraint.– Creates a unique index.– Disallows Nulls.

• UNIQUE constraint.– Creates a unique index.– Allows Nulls.

• UNIQUE index.

Page 5: SQL Server 7.0 Maintaining Referential Integrity.

FOREIGN KEY

• FOREIGN KEY constraint REFERENCES primary table’s PRIMARY KEY.

• It is recommended not to allow changes to the PRIMARY KEY, this may lead to the complex enforcement approach - Triggers.

Page 6: SQL Server 7.0 Maintaining Referential Integrity.

Relationship between two tables

• A typical Primary / Secondary table’s scenario.• Example: Orders and OrderDetails.

Page 7: SQL Server 7.0 Maintaining Referential Integrity.

Relationship in a Self-Referencing table

• A typical self-referencing table scenario.

• Example: Employees table, where each employee has a manager in charge; the manager is an employee himself.

Page 8: SQL Server 7.0 Maintaining Referential Integrity.

Four Referential Integrity rules

• Deleting a row from PrimaryTable is not allowed if there are related rows in SecondaryTable.

• An update to PrimaryTable.col1 is not allowed if there are related rows in SecondaryTable.

• An insert of a row into SecondaryTable is not allowed if there is no related row in PrimaryTable.

• An update to SecondaryTable.col1 is not allowed if there is no related row in PrimaryTable.

Page 9: SQL Server 7.0 Maintaining Referential Integrity.

FOREIGN KEY and REFERENCES constraint

The best way to enforce all those rules is to create a FOREIGN KEY and REFERENCES constraint, as the following statement shows:

ALTER TABLE SecondaryTable ADD CONSTRAINTFK_SecondaryTable_PrimaryTable FOREIGN KEY(col1)REFERENCES PrimaryTable(col1)We will use the same constraint to enforce Referential Integrity in the Self-Referencing table, as the following statement shows:

ALTER TABLE SelfRefTable ADD CONSTRAINTFK_SelfRefTable_SelfRefTable FOREIGN

KEY(col2)REFERENCES SelfRefTable(col1)

Page 10: SQL Server 7.0 Maintaining Referential Integrity.

Triggers and Cascading changes

• Things get complicated if we need to allow changes to PrimaryTable and cascade those changes to SecondaryTable.

• We need to decide whether to allow cascading DELETE and/or UPDATE operations.

• Constraints can not be used in this case.

Page 11: SQL Server 7.0 Maintaining Referential Integrity.

Choosing the right Referential

Integrity mechanism

Page 12: SQL Server 7.0 Maintaining Referential Integrity.

Cascading DELETE Operations

The following trigger achieves cascading DELETE operations from the PrimaryTable to the SecondaryTable:

CREATE TRIGGER dbo.TRG_cascade_delete ON PrimaryTable FOR DELETE AS

DELETE FROM SecTblFROM SecondaryTable SecTblINNER JOIN deleted dON SecTbl.col1 = d.col1

Page 13: SQL Server 7.0 Maintaining Referential Integrity.

Trigger

• Is a special kind of a stored procedure.

• Is invoked automatically for individual INSERT, UPDATE, DELETE operation, or a combination of those operations.

• Creates special areas in cache where it keeps the modified data, before and after the change.

• Is an implicit transaction.

• Now has 32 nesting levels.

• Can define more than one trigger of the same type on the same table.

Page 14: SQL Server 7.0 Maintaining Referential Integrity.

Cascade DELETE example

Page 15: SQL Server 7.0 Maintaining Referential Integrity.

Preventing a DELETE operation

If we decide not to cascade DELETE operations we need to enforce an invalid DELETE operation:

CREATE TRIGGER dbo.TRG_prevent_delete ON PrimaryTable FOR DELETE ASIF EXISTS (SELECT * FROM SecondaryTable SecTbl INNER JOIN

deleted d ON SecTbl.col1 = d.col1)

BEGIN RAISERROR('PrimaryTable has related rows in SecondaryTable.

TRANSACTION rolled back.', 10, 1) ROLLBACK TRANSACTIONEND

Page 16: SQL Server 7.0 Maintaining Referential Integrity.

Cascading UPDATE operations

CREATE TRIGGER dbo.TRG_cascade_update ON PrimaryTable FOR UPDATE ASDECLARE @numrows intSET @numrows = @@rowcountIF UPDATE(col1) IF @numrows = 1 UPDATE SecTbl SET col1 = (SELECT col1 FROM inserted) FROM deleted d INNER JOIN SecondaryTable SecTbl ON d.col1 = SecTbl.col1 ELSE IF @numrows > 1 BEGIN RAISERROR('Updates to more than one row in PrimaryTable are not allowed. TRANSACTION rolled back.', 10, 1) ROLLBACK TRANSACTION END

Page 17: SQL Server 7.0 Maintaining Referential Integrity.

Cascade UPDATE example

Page 18: SQL Server 7.0 Maintaining Referential Integrity.

Preventing invalid updates

CREATE TRIGGER dbo.TRG_prevent_update ON PrimaryTable FOR UPDATE ASIF EXISTS (SELECT * FROM SecondaryTable SecTbl INNER JOIN deleted d ON SecTbl.col1 = d.col1)BEGIN RAISERROR('PrimaryTable has related rows in SecondaryTable. TRANSACTION rolled back.', 10, 1) ROLLBACK TRANSACTIONEND

Page 19: SQL Server 7.0 Maintaining Referential Integrity.

Preventing invalid changes to the SecondaryTable

CREATE TRIGGER dbo.TRG_prevent_insupd ON SecondaryTable FOR INSERT, UPDATE ASDECLARE @numrows intSET @numrows = @@rowcountIF @numrows <> (SELECT COUNT(*) FROM PrimaryTable PrmTbl INNER JOIN inserted i ON PrmTbl.col1 = i.col1)BEGIN RAISERROR('Result rows in SecondaryTable do not have related rows in

PrimaryTable. TRANSACTION rolled back.', 10, 1) ROLLBACK TRANSACTIONEND

Page 20: SQL Server 7.0 Maintaining Referential Integrity.

Encapsulating the logic

sp_CreateRelationship

[@primary_table =] ‘primary table name’

,[@secondary_table =] ‘secondary table name’

,[@primary_col1 =] ‘primary column name_n’, [,…16]

,[@secondary_col1 =] ‘secondary column name_n’, [,…16]

[,[@cascade_updates =] 'true' | 'false']

[,[@cascade_deletes =] 'true' | 'false']

Implementing the stored procedure is just a matter of getting the user’s input and combining it in the ALTER TABLE ADD CONSTRAINT or CREATE TRIGGER commands.

Page 21: SQL Server 7.0 Maintaining Referential Integrity.

Summery

• A poorly designed database will lead to the use of complex, resource consuming mechanisms such as triggers.

• In most of the cases, a well-designed database will allow the use of the preferred mechanism – constraints.

• I presented deferent scenarios that need different approaches in implementing Referential Integrity.