CS422 Principles of Database Systems Stored Procedures and Triggers Chengyu Sun California State University, Los Angeles.

Slides:



Advertisements
Similar presentations
PL/SQL.
Advertisements

Chapter 8 Advanced SQL Pearson Education © Chapter 8 - Objectives u How to use the SQL programming language u How to use SQL cursors u How to create.
BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures.
AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
PL/SQL. Introduction to PL/SQL PL/SQL is the procedure extension to Oracle SQL. It is used to access an Oracle database from various environments (e.g.
SQL*PLUS, PLSQL and SQLLDR Ali Obaidi. SQL Advantages High level – Builds on relational algebra and calculus – Powerful operations – Enables automatic.
Chapter 4B: More Advanced PL/SQL Programming
A Guide to Oracle9i1 Advanced SQL And PL/SQL Topics Chapter 9.
Fundamentals, Design, and Implementation, 9/e Chapter 7 Using SQL in Applications.
SEMESTER 1, 2013/2014 DB2 APPLICATION DEVELOPMENT OVERVIEW.
Dr. James Dullea, CSC8490 Introduction to PL/SQLSlide 1 of 36 7From Prof. Dullea CSC8490 Introduction to PL/SQL Module 01-9 Revised: June 12, 2005 Dr.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall 7-1 David M. Kroenke’s Chapter Seven: SQL for Database Construction and.
Lecture 4 PL/SQL language. PL/SQL – procedural SQL Allows combining procedural and SQL code PL/SQL code is compiled, including SQL commands PL/SQL code.
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall 7-1 David M. Kroenke’s Chapter Seven: SQL for Database Construction and.
Stored procedures1 Stored procedures and functions Procedures and functions stored in the database.
Overview · What is PL/SQL · Advantages of PL/SQL · Basic Structure of a PL/SQL Block · Procedure · Function · Anonymous Block · Types of Block · Declaring.
Programming in postgreSQL with PL/pgSQL ProceduralLanguageextension topostgreSQL.
Advanced SQL: Cursors & Stored Procedures
Advanced SQL Instructor: Mohamed Eltabakh 1 Part II.
CS178 Database Management PL/SQL session 8 References: ORACLE 9i PROGRAMMING A Primer Rajshekhar Sunderraman.
CIS4368: Advanced DatabaseSlide # 1 PL/SQL Dr. Peeter KirsSpring, 2003 PL/SQL.
PL/SQL Block Structure DECLARE - Optional Variables, cursors, user-defined exceptions BEGIN - Mandatory SQL Statements PL/SQL Statements EXCEPTIONS - Optional.
Trigger Oracle PL/SQL. Triggers Associated with a particular table Associated with a particular table Automatically executed when a particular event occurs.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
Commercial RDBMSs Access and Oracle. Access DBMS Architchecture  Can be used as a standalone system on a single PC: -JET Engine -Microsoft Data Engine.
Advanced SQL: Triggers & Assertions
What is a Package? A package is an Oracle object, which holds other objects within it. Objects commonly held within a package are procedures, functions,
Objectives Database triggers and syntax
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
A Guide to SQL, Eighth Edition Chapter Eight SQL Functions and Procedures.
Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha Stored Procedure used in PosgreSQL.
Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha Function, Trigger used in PosgreSQL.
Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha Views, Sequence, and Stored Procedure used in PosgreSQL.
Learningcomputer.com SQL Server 2008 –Views, Functions and Stored Procedures.
A procedure is a module performing one or more actions; it does not need to return any values. The syntax for creating a procedure is as follows: CREATE.
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
IT420: Database Management and Organization Triggers and Stored Procedures 24 February 2006 Adina Crăiniceanu
Chapter 8 Advanced SQL Pearson Education © Chapter 8 - Objectives How to use the SQL programming language How to use SQL cursors How to create stored.
Kingdom of Saudi Arabia Ministry of Higher Education Al-Imam Muhammad Ibn Saud Islamic University College of Computer and Information Sciences Overview.
SQL Triggers, Functions & Stored Procedures Programming Operations.
Introduction to PL/SQL N. Dimililer. About PL/SQL –PL/SQL is an extension to SQL with design features of programming languages. –Data manipulation and.
1 Section 10 - Embedded SQL u Many computer languages allow you to embed SQL statements within the code (e.g. COBOL, PowerBuilder, C++, PL/SQL, etc.) u.
Programming in postgreSQL with PL/pgSQL ProceduralLanguageextension topostgreSQL 1.
CS422 Principles of Database Systems Oracle PL/SQL Chengyu Sun California State University, Los Angeles.
Programming in postgreSQL with PL/pgSQL
Programming in postgreSQL with PL/pgSQL
Trigger used in PosgreSQL
User Defined Functions and Triggers Tutorial
Tables and Triggers.
Creating Database Triggers
CMSC-461 Database Management Systems
PostgreSQL Conference East 2009
PL/SQL.
UNIT - V STORED PROCEDURE.
Stored Procedure used in PosgreSQL
CS4222 Principles of Database System
Stored Procedure used in PosgreSQL
Stored Procedure used in PosgreSQL
Stored Procedure used in PosgreSQL
Database Processing: David M. Kroenke’s Chapter Seven:
Oracle9i Developer: PL/SQL Programming Chapter 8 Database Triggers.
Chapter 7 Using SQL in Applications
CS3220 Web and Internet Programming SQL and MySQL
Information Management
Chapter 8 Advanced SQL Pearson Education © 2009.
CodePainter Revolution Trainer Course
Prof. Arfaoui. COM390 Chapter 9
Modification to Views Via Triggers
CS3220 Web and Internet Programming SQL and MySQL
Presentation transcript:

CS422 Principles of Database Systems Stored Procedures and Triggers Chengyu Sun California State University, Los Angeles

Stored Procedures User-created functions that are stored in the database just like other schema elements Procedure vs. Function A procedure does not return any value, while a function does In PostgreSQL, a procedure is simply a function that returns void

Example: Hello World create function hello() returns void as $$ begin raise notice 'Hello world in PL/pgSQL'; end; $$ language plpgsql;

Example: Add10 create function add10( a integer ) returns integer as $$ declare b integer; begin b := 10; return a + b; end; $$ language plpgsql;

Procedural Language (PL) A programming language for writing stored procedures Usually based on some existing language like SQL, Java, C#, Perl, Python … E.g. PL/SQL, PL/Java, PL/Perl …

Why Use Stored Procedures? Performance compiled and optimized code Save communication overhead Security Access control Less data transferred over the wire Simplify application code Triggers for data integrity

Why Not To Use Stored Procedures? Portability PL are generally more difficult to develop and maintain than conventional programming languages Less language features Less tool support

PostgreSQL PL/pgSQL SQL + things you would expect from a conventional programming language: Variables and types Control flow statements Functions /interactive/plpgsql.html

Elements of a Programming Language Comments Literals Variables and Types Operators and expressions Statements Special statements, e.g. input and output Functions Classes Packages

Elements of PL/pgSQL Comments Literals Variables and types Operators and expression Statements Functions Classes Packages Same as in SQL Mostly the same as in SQL, with a few special types and operators Not supported

Basic Function Syntax CREATE [OR REPLACE] FUNCTION name ( parameters ) RETURNS type AS $$ DECLARE declarations BEGIN statements END; $$ LANGUAGE plpgsql; DROP FUNCTION name ( argtype [,...]);

Examples: Basics hello() add10() Implement a function that takes two integer parameters and displays the sum

Basic Syntax and Output Variable declaration The assignment operator := RAISE Levels: DEBUG, LOG, INFO, NOTICE, WARNING, EXCEPTION Format output with % eractive/plpgsql-errors-and-messages.html eractive/plpgsql-errors-and-messages.html

Naming Conventions We want to avoid name conflicts among variables, tables, and columns A simple naming convention: Prefix parameters with p_ Prefix local variable with l_ Prefix package global variable with g_

Examples: Statements Implement a function that returns the name of a student given the student’s id; output a warning message if no student is found Implement a function that calculates factorial

SELECT…INTO SELECT result must be a single row. SELECT select_list INTO variable_list FROM table_list [WHERE condition] [ORDER BY order_list];

Branch Statement NOTE: don’t forget the semicolon (;) after END IF. IF condition1 THEN statements1 ELSIF condition2 THEN statements2 ELSE statements3 END IF;

Loop Statements LOOP statements EXIT WHEN condition; statements END LOOP; WHILE condition LOOP statements END LOOP; FOR loop_variable IN [REVERSE] lower_bound..upper_bound LOOP statements END LOOP;

Examples: Types Implement a function that randomly returns two student records

Special Types Each table defines a type %ROWTYPE %TYPE SetOf Cursor

Examples: Cursor Implement a function that randomly returns 20% of the students

Cursor An iterator for a collection of records We can use a cursor to process the rows returned by a SELECT statement

Using Cursors Declaration Unbound cursor: refcursor Bound cursor: cursor for OPEN FETCH CLOSE

Cursor - Open OPEN cursor [FOR query] The query is executed The position of the cursor is before the first row of the query results

Cursor - Fetch FETCH cursor INTO target Move the cursor to the next row Return the row A special variable FOUND is set to true

Cursor - Fetch FETCH cursor INTO target Move the cursor to the next row Return the row A special variable FOUND is set to true

Cursor - Fetch If there is no next row target is set to NULL(s) The special variable FOUND is set to false

Cursor - Close CLOSE cursor ;

Query FOR Loop FOR target IN query LOOP statements END LOOP;

About PL Programming It’s just programming like you always do Debug code one small piece at a time Ask “How to do X” questions in the class forum Avoid re-implementing SQL For example, to compute max(price), use SELECT MAX(price) instead of using a cursor to iterate through all rows

Triggers Procedures that are automatically invoked when data is changed, i.e. INSERT, DELETE, and UPDATE. Common use of triggers Enforcing data integrity constraints Auditing Replication

Trigger Example Create a trigger that audit the changes to the grades in the enrollment table create table grade_changes ( enrollment_idinteger, old_grade_idinteger, new_grade_idinteger,timestamp );

Trigger Example: Trigger create trigger grade_audit after update on enrollment for each row execute procedure grade_audit();

Trigger Syntax CREATE TRIGGER name { BEFORE | AFTER } { event [ OR... ] } ON table [ FOR EACH { ROW | STATEMENT } ] EXECUTE PROCEDURE funcname ( arguments ); DROP TRIGGER name ON table;

Triggering Events INSERT DELETE UPDATE

Before or After BEFORE : trigger fires before the triggering event AFTER : trigger fires after the event

Statement Trigger vs. Row Trigger Statement Trigger Default Fires once per statement Row Trigger FOR EACH ROW Fires once per row

Trigger Example: Function create or replace function grade_audit() returns trigger as $$ begin if new.id = old.id and new.grade_id <> old.grade_id then insert into grade_changes values ( new.id, old.grade_id, new.grade_id, current_timestamp ); end if; return null; end; $$ language plpgsql;

About Trigger Functions No parameters Return type must be trigger Special variables NEW, OLD Others: eractive/plpgsql-trigger.html eractive/plpgsql-trigger.html

Return Value of a Trigger Function Statement triggers and after-row triggers should return NULL Before-row trigger can return NULL to skip the operation on the current row For before-row insert and update triggers, the returned row becomes the row that will be inserted or will replace the row being updated

Examples: Enforce Data Integrity Constraints Create a trigger to enforce the constraint that the size of a Database class cannot exceed 30 RAISE EXCEPTION would abort the statement