14 Triggers / Embedded SQL



Similar documents
Procedural Extension to SQL using Triggers. SS Chung

Programming Database lectures for mathema

COMS20700 DATABASES 13 PL/SQL. COMS20700 Databases Dr. Essam Ghadafi

1 Triggers. 2 PL/SQL Triggers

9 Using Triggers. Using Triggers 9-1

Programming in postgresql with PL/pgSQL. Procedural Language extension to postgresql

ORACLE 9I / 10G / 11G / PL/SQL COURSE CONTENT

Objectives of SQL. Terminology for Relational Model. Introduction to SQL

PL/SQL. Database Procedural Programming PL/SQL and Embedded SQL. Procedures and Functions

Oracle Database 10g: Program with PL/SQL

SQL Programming. CS145 Lecture Notes #10. Motivation. Oracle PL/SQL. Basics. Example schema:

Embedded SQL programming

Chapter 9, More SQL: Assertions, Views, and Programming Techniques

Oracle Database: SQL and PL/SQL Fundamentals

Embedded SQL. Unit 5.1. Dr Gordon Russell, Napier University

Darshan Institute of Engineering & Technology PL_SQL

SQL is capable in manipulating relational data SQL is not good for many other tasks

Introduction to Triggers using SQL

More SQL: Assertions, Views, and Programming Techniques

Database programming 20/08/2015. DBprog news. Outline. Motivation for DB programming. Using SQL queries in a program. Using SQL queries in a program

Elena Baralis, Silvia Chiusano Politecnico di Torino. Pag. 1. Active database systems. Triggers. Triggers. Active database systems.

RDBMS Using Oracle. Lecture Week 7 Introduction to Oracle 9i SQL Last Lecture. kamran.munir@gmail.com. Joining Tables

Oracle Database: SQL and PL/SQL Fundamentals NEW

Database Programming with PL/SQL: Learning Objectives

A basic create statement for a simple student table would look like the following.

Intro to Embedded SQL Programming for ILE RPG Developers

SQL NULL s, Constraints, Triggers

Oracle Database: SQL and PL/SQL Fundamentals

In This Lecture. SQL Data Definition SQL SQL. Notes. Non-Procedural Programming. Database Systems Lecture 5 Natasha Alechina

Oracle Database 10g Express

Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer.

5.1 Database Schema Schema Generation in SQL

Teach Yourself InterBase

Handling Exceptions. Copyright 2006, Oracle. All rights reserved. Oracle Database 10g: PL/SQL Fundamentals 8-1

Handling PL/SQL Errors

Oracle Database: Program with PL/SQL

Instant SQL Programming

Oracle(PL/SQL) Training

Writing Control Structures

Oracle 10g PL/SQL Training

Oracle SQL, introduced in the previous chapter, is not a language that can be

Oracle Database 12c: Introduction to SQL Ed 1.1

Duration Vendor Audience 5 Days Oracle Developers, Technical Consultants, Database Administrators and System Analysts

Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer.

Oracle Database 10g: Introduction to SQL

Oracle 11g PL/SQL training

ERserver. DB2 Universal Database for iseries SQL Programming with Host Languages. iseries. Version 5

Triggers & Packages. {INSERT [OR] UPDATE [OR] DELETE}: This specifies the DML operation.

Chapter 13. Introduction to SQL Programming Techniques. Database Programming: Techniques and Issues. SQL Programming. Database applications

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff

Creating PL/SQL Blocks. Copyright 2007, Oracle. All rights reserved.

PL/SQL Overview. Basic Structure and Syntax of PL/SQL

Oracle Database: Program with PL/SQL

T-SQL STANDARD ELEMENTS

In This Lecture. Security and Integrity. Database Security. DBMS Security Support. Privileges in SQL. Permissions and Privilege.

Handling PL/SQL Errors

Oracle SQL. Course Summary. Duration. Objectives

Retrieving Data Using the SQL SELECT Statement. Copyright 2006, Oracle. All rights reserved.

Oracle Database: Program with PL/SQL

Training Guide. PL/SQL for Beginners. Workbook

SQL Databases Course. by Applied Technology Research Center. This course provides training for MySQL, Oracle, SQL Server and PostgreSQL databases.

Using SQL in RPG Programs: An Introduction

Oracle Database: Program with PL/SQL

Oracle For Beginners Page : 1

5. CHANGING STRUCTURE AND DATA

Handling Exceptions. Schedule: Timing Topic. 45 minutes Lecture 20 minutes Practice 65 minutes Total

D61830GC30. MySQL for Developers. Summary. Introduction. Prerequisites. At Course completion After completing this course, students will be able to:

SQL. Short introduction

Course Objectives. Database Applications. External applications. Course Objectives Interfacing. Mixing two worlds. Two approaches

Programming with SQL

Using ORACLE in the CSLab

SQL/PSM. Outline. Database Application Development Oracle PL/SQL. Why Stored Procedures? Stored Procedures PL/SQL. Embedded SQL Dynamic SQL

Oracle For Beginners Page : 1

AUTHENTICATION... 2 Step 1:Set up your LDAP server... 2 Step 2: Set up your username... 4 WRITEBACK REPORT... 8 Step 1: Table structures...

Oracle Database: Program with PL/SQL

Oracle Database: SQL and PL/SQL Fundamentals NEW

CS346: Database Programming.

Handling Exceptions. Schedule: Timing Topic 45 minutes Lecture 20 minutes Practice 65 minutes Total

Chapter 9 Java and SQL. Wang Yang wyang@njnet.edu.cn

Embedding SQL in High Level Language Programs

SQL Server Database Coding Standards and Guidelines

Oracle PL/SQL Best Practices

Database Query 1: SQL Basics

How To Create A Table In Sql (Ahem)

Real SQL Programming. Persistent Stored Modules (PSM) PL/SQL Embedded SQL

Maintaining Stored Procedures in Database Application

Fine Grained Auditing In Oracle 10G

2874CD1EssentialSQL.qxd 6/25/01 3:06 PM Page 1 Essential SQL Copyright 2001 SYBEX, Inc., Alameda, CA

BCA. Database Management System

Databasesystemer, forår 2005 IT Universitetet i København. Forelæsning 3: Business rules, constraints & triggers. 3. marts 2005

ATTACHMENT 6 SQL Server 2012 Programming Standards

Introduction to SQL and database objects

The Structured Query Language. De facto standard used to interact with relational DB management systems Two major branches

Schema Evolution in SQL-99 and Commercial (Object-)Relational DBMS

Oracle Database 11g: Program with PL/SQL

MySQL for Beginners Ed 3

Oracle9i: Develop PL/SQL Program Units

CSC 443 Database Management Systems. The SQL Programming Language

Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification

Transcription:

14 Triggers / Embedded SQL COMS20700 Databases Dr. Essam Ghadafi

TRIGGERS A trigger is a procedure that is executed automatically whenever a specific event occurs. You can use triggers to enforce constraints and do other stuff.

TRIGGERS Syntax: CREATE [OR REPLACE] TRIGGER <trigger_name> {BEFORE AFTER} {INSERT DELETE UPDATE} ON <table_name> [REFERENCING [NEW AS <new_name>] [OLD AS <old_name>]] [FOR EACH ROW [WHEN (<trigger_condition>)]] [ Declare /* Declaration Section */ ] BEGIN /* Trigger Body */ END [<trigger_name>];

TYPES OF EVENTS DML statements: INSERT, UPDATE, DELETE on a particular table or view. DDL statements: CREATE, ALTER, DROP. Database events: e.g., LOG ON, LOG OFF, STARTUP, SHUTDOWN,...

TRIGGERS Trigger Event - The triggering SQL statement: INSERT UPDATE DELETE Timing - When the trigger is fired: BEFORE Fires before the triggering SQL statement is executed. AFTER Fires after the triggering SQL statement is executed. Level: STATEMENT Executes once for each transaction (Default). ROW Executes once for each row in a transaction.

NEW AND OLD OLD.<attribute name> The value of the attribute before a change from an UPDATE statement or before a DELETE statement. This value is NULL for INSERT statements. NEW.<attribute name> The value of the attribute after an UPDATE/INSERT statement. This value is NULL for DELETE statements. Can be aliased NEW AS newname OLD AS oldname Note: Those are preceded by a colon in the body but not in the WHEN clause.

TRIGGER EXAMPLES Example1: Trigger salarycheck enforces a check constraint. CREATE TRIGGER salarycheck AFTER INSERT OR UPDATE OF salary ON Employee FOR EACH ROW BEGIN IF (:new.salary < 0) THEN RAISE_APPLICATION_ERROR(-20000, salary is < 0 ); END IF; END salarycheck; /

TRIGGERS EXAMPLES Example2: Trigger addhigh inserts records into HighIncome table whenever they are added to the Employee table with a salary > 3000. CREATE TRIGGER addhigh AFTER INSERT ON Employee REFERENCING NEW AS newrow FOR EACH ROW WHEN (newrow.salary >3000) BEGIN INSERT INTO HighIncome VALUES(:newRow.name, :newrow.salary); END addhigh;

EXECUTION MODEL Execute all BEFORE statement triggers that apply. Loop for each row affected by the SQL statement Execute all BEFORE row triggers that apply. Change the row. Perform integrity constraint checking. Execute all AFTER row triggers that apply. Complete integrity constraint checking. Execute all AFTER statement triggers that apply.

MULTIPLE TRIGGER EVENTS How to tell which statement fired the trigger? Use the flags: INSERTING, UPDATING and DELETING. IF INSERTING THEN... ELSIF UPDATING THEN... ELSIF Deleting THEN... ELSE... END IF;

TRIGGERS Displaying Trigger Definition Errors If you get a message Warning: "Trigger created with compilation errors.". You can see the error messages by typing: SHOW ERRORS TRIGGER <trigger_name>; Alternatively, check the User_Errors table...

TRIGGERS Listing Your Defined Triggers To view a list of all your defined triggers, see table User_Triggers Deleting a Trigger DROP TRIGGER <trigger_name>; Temporarily Disabling a Trigger ALTER TRIGGER <trigger_name> DISABLE; To re-enable the trigger: ALTER TRIGGER <trigger_name> ENABLE;

TRIGGERS Disabling/Enabling all Triggers on a Table ALTER TABLE <table_name> ENABLE ALL TRIGGERS; ALTER TABLE <table_name> DISABLE ALL TRIGGERS; Note: When you drop a table, all triggers on that table will be deleted automatically. To create a TRIGGER, you must have either of the privileges: CREATE TRIGGER CREATE ANY TRIGGER

FINAL EXAMPLE Keeping a log of all deletions from table Employee. Suppose that many users are authorized to delete from the table. GRANT DELETE ON <table_name> TO <user_name>; CREATE TABLE EmpDelLog ( username VARCHAR2(10), deletion_time DATE, empno Number ); We write the trigger: CREATE TRIGGER empdelete BEFORE DELETE ON Employee FOR EACH ROW BEGIN INSERT INTO EmpDelLog VALUES(USER, SYSDATE, :OLD.empno); END empdelete;

MUTATING TABLES You get a mutating table error if you try to modify or read from the table associated with the trigger within a row-level trigger, i.e. trying to access rows that are currently in the state of change. Solution: If you have to access the table associated with the trigger withing the trigger, define the trigger as a statement-level trigger not a row-level trigger.

MUTATING TABLES Example: CREATE OR REPLACE TRIGGER Employee_Check AFTER INSERT ON Employee For each row Declare sal Employee.salary%TYPE; BEGIN SELECT salary INTO sal FROM Employee WHERE empno=9041; END Employee_Check; / INSERT INTO Employee values (10203, Paul Ryan, 2450); You will get the following Error: Error: ORA-04091: table UserName.Employee is mutating, trigger/function may not see it

EMBEDDED SQL (OVERVIEW) Combines the powerful capabilities of a high-level language (C/C++,.Net, COBOL, Java,... etc.) with the database manipulation capabilities of SQL. SQL statements can be executed from any application program. Oracle has an environment called Pro*C/C++ which one can use to write C/C++ programs that incorporate SQL statements. The precompiler first replaces the SQL code in the program with C/C++ code. The whole C/C++ program is then compiled by the language compiler.

EMBEDDED SQL Pro*C Communication between the program and the database is via host variables. All SQL statements start with EXEC SQL and end with a semicolon. Example: int ageval; int empnoval; printf("enter the Employee Number:"); scanf("%d",&empnoval); EXEC SQL SELECT age INTO :ageval FROM Employee WHERE empno=:empnoval; printf("the age is %d\n", ageval);

DYNAMIC SQL If you use fixed SQL statements, then you need to recompile the program every time you need to change them... Dynamic SQL allows executing dynamically generated SQL statements. For dynamic SQL, we need: 1 PREPARE: To convert a string into a SQL statement. 2 EXECUTE: To execute the SQL statement.

DYNAMIC SQL Example-1: char *s = "INSERT INTO Emp VALUES(567, Chris, 3400)"; EXEC SQL PREPARE query FROM :s; EXEC SQL EXECUTE query; Alternatively, one can combine PREPARE and EXECUTE using EXECUTE IMMEDIATE. Example-2: char *s = "INSERT INTO Emp VALUES(567, Chris, 3400)"; EXEC SQL EXECUTE IMMEDIATE :s;