Upload
leon-carr
View
236
Download
1
Tags:
Embed Size (px)
Citation preview
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.
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.
Entity Integrity
• PRIMARY KEY constraint.– Creates a unique index.– Disallows Nulls.
• UNIQUE constraint.– Creates a unique index.– Allows Nulls.
• UNIQUE index.
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.
Relationship between two tables
• A typical Primary / Secondary table’s scenario.• Example: Orders and OrderDetails.
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.
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.
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)
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.
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
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.
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
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
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
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
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.
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.