SQL Server 7.0 Maintaining Referential Integrity.

Slides:



Advertisements
Similar presentations
DB glossary (focus on typical SQL RDBMS, not XQuery or SPARQL)
Advertisements

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Batches, Scripts, Transactions-SQL Server 7. A batch is a set of Transact-SQL statements that are interpreted together by SQL Server. They are submitted.
MSc IT UFCE8K-15-M Data Management Prakash Chatterjee Room 2Q18
1 Constraints, Triggers and Active Databases Chapter 9.
Database Management Systems, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
Module 5: Implementing Data Integrity. Overview Types of Data Integrity Enforcing Data Integrity Defining Constraints Types of Constraints Disabling Constraints.
Introduction to Structured Query Language (SQL)
Fundamentals, Design, and Implementation, 9/e Chapter 11 Managing Databases with SQL Server 2000.
1 Relational Model. 2 Relational Database: Definitions  Relational database: a set of relations  Relation: made up of 2 parts: – Instance : a table,
SQL Keys and Constraints Justin Maksim. Key Declaration Key constraint defined within the CREATE TABLE command Key can be declared using either the PRIMARY.
Database Systems More SQL Database Design -- More SQL1.
Introduction to Structured Query Language (SQL)
Data Integrity Constraints
SQL DDL constraints Restrictions on the columns and tables 1SQL DDL Constraints.
1 Chapter 2 Reviewing Tables and Queries. 2 Chapter Objectives Identify the steps required to develop an Access application Specify the characteristics.
INTEGRITY Enforcing integrity in Oracle. Oracle Tables mrobbert owner granted access.
Database Constraints. Database constraints are restrictions on the contents of the database or on database operations Database constraints provide a way.
Chapter 7 Constraints and Triggers Spring 2011 Instructor: Hassan Khosravi.
Chapter 14 & 15 Conceptual & Logical Database Design Methodology
The Relational Model These slides are based on the slides of your text book.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor Ms. Arwa.
CSE314 Database Systems More SQL: Complex Queries, Triggers, Views, and Schema Modification Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson.
An Investigation of Oracle and SQL Server with respect to Integrity, and SQL Language standards Presented by: Paul Tarwireyi Supervisor: John Ebden Date:
Introduction to SQL Steve Perry
Constraints  Constraints are used to enforce rules at table level.  Constraints prevent the deletion of a table if there is dependencies.  The following.
Lecture 7 Integrity & Veracity UFCE8K-15-M: Data Management.
DAY 12: DATABASE CONCEPT Tazin Afrin September 26,
FALL 2004CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
ICS 321 Fall 2011 Constraints, Triggers, Views & Indexes Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Dec 8, 2003Murali Mani Constraints B term 2004: lecture 15.
Constraints cis 407 Types of Constraints & Naming Key Constraints Unique Constraints Check Constraints Default Constraints Misc Rules and Defaults Triggers.
1 SQL - II Data Constraints –Applying data constraints Types of data constraints –I/O constraints The PRIMARY KEY constraints The FOREIGN KEY constraints.
Chapter 9 Constraints. Chapter Objectives  Explain the purpose of constraints in a table  Distinguish among PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK,
Oracle 11g: SQL Chapter 4 Constraints.
Module 4: Implementing Data Integrity
Chapter 4 Constraints Oracle 10g: SQL. Oracle 10g: SQL 2 Objectives Explain the purpose of constraints in a table Distinguish among PRIMARY KEY, FOREIGN.
Constraints and Triggers. What’s IC? Integrity Constraints define the valid states of SQL-data by constraining the values in the base tables. –Restrictions.
06 | Modifying Data in SQL Server Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
Chapter 9 Logical Database Design : Mapping ER Model To Tables.
Constraints Lesson 8. Skills Matrix Constraints Domain Integrity: A domain refers to a column in a table. Domain integrity includes data types, rules,
DATA AND SCHEMA MODIFICATIONS CHAPTERS 4,5 (6/E) CHAPTER 8 (5/E) 1.
Chapter 5 : Integrity And Security  Domain Constraints  Referential Integrity  Security  Triggers  Authorization  Authorization in SQL  Views 
Session 1 Module 1: Introduction to Data Integrity
Learningcomputer.com SQL Server 2008 –Views, Functions and Stored Procedures.
Relational Database Management System(RDBMS) Structured Query Language(SQL)
IMS 4212: Constraints & Triggers 1 Dr. Lawrence West, Management Dept., University of Central Florida Stored Procedures in SQL Server.
Constraints and Views Chap. 3-5 continued (7 th ed. 5-7)
Constraints Advanced Database Systems Dr. AlaaEddin Almabhouh.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
1 CS122A: Introduction to Data Management Lecture #4 (E-R  Relational Translation) Instructor: Chen Li.
CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
1 Agenda TMA02 M876 Block 4. 2 Model of database development data requirements conceptual data model logical schema schema and database establishing requirements.
In this session, you will learn to: Manage databases Manage tables Objectives.
Data Integrity & Indexes / Session 1/ 1 of 37 Session 1 Module 1: Introduction to Data Integrity Module 2: Introduction to Indexes.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Getting started with Accurately Storing Data
Chapter 6 - Database Implementation and Use
Constraints and Triggers
Implementing Triggers
Module 5: Implementing Data Integrity by Using Constraints
Referential Integrity
Constraints.
SQL DATA CONSTRAINTS.
Contents Preface I Introduction Lesson Objectives I-2
Chapter 11 Managing Databases with SQL Server 2000
Responding to Data Manipulation Via Triggers
Presentation transcript:

SQL Server 7.0 Maintaining Referential Integrity

SQL Server is a R DBMS 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 CONSTRAINT FK_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 CONSTRAINT FK_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.

Choosing the right Referential Integrity mechanism

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 SecTbl FROM SecondaryTable SecTbl INNER JOIN deleted d ON 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.

Cascade DELETE example

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 AS IF 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 TRANSACTION END

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

Cascade UPDATE example

Preventing invalid updates CREATE TRIGGER dbo.TRG_prevent_update ON PrimaryTable FOR UPDATE AS IF 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 TRANSACTION END

Preventing invalid changes to the SecondaryTable CREATE TRIGGER dbo.TRG_prevent_insupd ON SecondaryTable FOR INSERT, UPDATE AS int = <> (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 TRANSACTION END

Encapsulating the logic sp_CreateRelationship =] ‘primary table =] ‘secondary table =] ‘primary column name_n’, =] ‘secondary column name_n’, [,…16] =] 'true' | 'false'] =] '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.