Oracle Tutorials, CERN, Geneva, 21 st May 2013 Zbigniew Baranowski.

Slides:



Advertisements
Similar presentations
BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures.
Advertisements

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.
PL/SQL.
1 Copyright © 2004, Oracle. All rights reserved. Creating Stored Procedures.
A Guide to Oracle9i1 Advanced SQL And PL/SQL Topics Chapter 9.
PL/SQL Agenda: Basic PL/SQL block structure
Oracle PL/SQL Eyad Husni Elshami. Why PL/SQL Block Structures: – PL/SQL consists of blocks of code, which can be nested within each other. Each block.
Introduction to PL/SQL Lecture 0 – Self Study Akhtar Ali.
Oracle Tutorials: PL/SQL
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.
Introduction to PL/SQL. Procedural Language extension for SQL Oracle Proprietary 3GL Capabilities Integration of SQL Portable within Oracle data bases.
Bordoloi and Bock CURSORS. Bordoloi and Bock CURSOR MANIPULATION To process an SQL statement, ORACLE needs to create an area of memory known as the context.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
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.
INTRODUCTION TO PL/SQL. Class Agenda Introduction Introduction to PL/SQL Declaring PL/SQL Variable Creating the Executable Section Interacting with the.
Program with PL/SQL. Interacting with the Oracle Server.
Overview · What is PL/SQL · Advantages of PL/SQL · Basic Structure of a PL/SQL Block · Procedure · Function · Anonymous Block · Types of Block · Declaring.
PL/SQL A BRIEF OVERVIEW DAVID WILSON. PL/SQL User’s Guide and Reference PL/SQL User’s Guide and Reference.
PL / SQL By Mohammed Baihan. What is PL/SQL? PL/SQL stands for Procedural Language extension of SQL. PL/SQL is a combination of SQL along with the procedural.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
PL/SQL Block Structure DECLARE - Optional Variables, cursors, user-defined exceptions BEGIN - Mandatory SQL Statements PL/SQL Statements EXCEPTIONS - Optional.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
Database Application Development using PL/SQL Programming.
Guide to Oracle 10g ITBIS373 Database Development Lecture 4a - Chapter 4: Using SQL Queries to Insert, Update, Delete, and View Data.
SQL Fundamentals  SQL: Structured Query Language is a simple and powerful language used to create, access, and manipulate data and structure in the database.
School of Computing and Management Sciences © Sheffield Hallam University SQL is non-procedural –designed to be relatively approachable to non- programmers.
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.
Using SQL in PL/SQL ITEC 224 Database Programming.
Dynamic SQL. 2 home back first prev next last What Will I Learn? Recall the stages through which all SQL statements pass Describe the reasons for using.
PL/SQLPL/SQL Oracle11g: PL/SQL Programming Chapter 9 Database Triggers.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
DATABASE PROGRAMS CS 260 Database Systems. Overview  Introduction  Anonymous blocks  Oracle’s PL/SQL language basics  Conditions and loops  Cursors.
PL/SQL. What is PL/SQL  Procedural Language – SQL  An extension to SQL with design features of programming languages (procedural and object oriented)
PRACTICE OVERVIEW PL/SQL Part Your stored procedure, GET_BUDGET, has a logic problem and must be modified. The script that contains the procedure.
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
Introduction to PL/SQL Francis Thottungal. The outline The basic PL/SQL code structure is : DECLARE -- optional, which declares and define variables,
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.
PL/SQL  PL/SQL stands for Procedural Language/SQL.  PL/SQL extends SQL by adding constructs found in procedural languages like procedures, loops, variables,
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.
Stored Procedures and Functions Pemrograman Basis Data MI2183.
Database An introduction to using Oracle PL/SQL An introduction to using Oracle PL/SQL An introduction to using Oracle PL/SQL Definition: PL/SQL.
CS422 Principles of Database Systems Oracle PL/SQL Chengyu Sun California State University, Los Angeles.
CS422 Principles of Database Systems Stored Procedures and Triggers Chengyu Sun California State University, Los Angeles.
Oracle9i Developer: PL/SQL Programming Chapter 6 PL/SQL Packages.
Preface IIntroduction Course Objectives I-2 Oracle Complete Solution I-3 Course Agenda I-4 Tables Used in This Course I-5 The Order Entry Schema I-6 The.
1 Copyright © 2004, Oracle. All rights reserved. PL/SQL Programming Concepts: Review.
6 Copyright © 2009, Oracle. All rights reserved. Using Dynamic SQL.
PL/SQL MULTIPLE CHOICE QUESTION.
Creating Database Triggers
Interacting with the Oracle Server
Creating Stored Procedures and Functions
Interacting with the Oracle Server
PL/SQL.
SQL Stored Triggers Presented by: Dr. Samir Tartir
UNIT - V STORED PROCEDURE.
Database Management Systems 2
PL/SQL Scripting in Oracle:
Chapter 2 Handling Data in PL/SQL Blocks Oracle9i Developer:
PL/SQL week10.
Oracle9i Developer: PL/SQL Programming Chapter 8 Database Triggers.
Chapter 8 Advanced SQL.
PL/SQL Declaring Variables.
Chapter 8 Advanced SQL Pearson Education © 2009.
Prof. Arfaoui. COM390 Chapter 9
Presentation transcript:

Oracle Tutorials, CERN, Geneva, 21 st May 2013 Zbigniew Baranowski

PL/SQL basics Outline Overview of PL/SQL Blocks Variables and placeholders Program Flow Control Statements Cursors Functions and Procedures Error Handling Packages Triggers Jobs

PL/SQL basics PL/SQL  Procedural language extension to SQL  procedural data manipulation  fully supports SQL data types  Integrated with the ORACLE database server  Server-side compilation execution  End-user platform independent (like SQL)  High-level language features  Complex data types  Data encapsulation  Modular programming 3

PL/SQL basics Writing PL/SQL programs  Each program is a block consisting of  PL/SQL statements – logic  SQL statements – data manipulation  Type of block  Named / Stored (on the database)  Anonymous External scripts (file or input) Nested blocks 4

PL/SQL basics PL/SQL Block Structure DECLARE l_commission NUMBER; L_COMM_MISSING EXCEPTION; BEGIN SELECT commission_pct / 100 INTO l_commission FROM employees WHERE employee_id = emp_id; IF l_commission IS NULL THEN RAISE COMM_MISSING; ELSE UPDATE employees SET salary = salary + bonus*l_commission WHERE employee_id = emp_id; END IF; EXCEPTION WHEN L_COMM_MISSING THEN DBMS_OUTPUT.PUT_LINE('This employee does not receive a commission.'); END; / 5 block body declaration section exception section

PL/SQL basics PL/SQL execution 6

PL/SQL basics Important PL/SQL delimiters +, -, *, / arithmetic operators ; statement terminator := assignment operator => association operator || strings concatenation operator. component indicator % attribute operator ‘ character string delimiter -- single line comment /*, */ multi line comment delimiters.. range operator =, >, >=, <, <= relational operators !=, ~=, ^=, <> not equal relational operators is null, like, between PL/SQL relational operators 7

PL/SQL basics PL/SQL placeholders  All SQL types are supported by PL/SQL  Numerical types NUMBER, PLS_INTEGER Many derived types, e.g. POSITIVE  Character types CHAR, VARCHAR2, NCHAR,…  Other scalar types BOOLEAN, DATE, UROWID RAW, BLOB, CLOB  Some types can have bigger max sizes then in SQL 8

PL/SQL basics PL/SQL placeholders  Scalar type  variable  constant  Composite/vector type  record - used for reading rows from table  Collections  associative array - dictionary  variable-sized array – fixed size  nested tables – dynamic size 9

PL/SQL basics PL/SQL placeholders  Scalar type  variable  constant DECLARE l_x NUMBER := 20000; l_message VARCHAR2(40); C_PI CONSTANT NUMBER(3,2):=3.14; BEGIN l_x := 1000 * C_PI; l_message := 'Hello world'; END; / 10

PL/SQL basics PL/SQL placeholders  Scalar type  variable  constant  Single composite/vector type  record - used for reading rows from table  Collections  Associative Array  Variable-sized Array (VARRAY)  Nested Tables TYPE T_TIME IS RECORD (minutes INTEGER, hours NUMBER(2)); current_time_rec T_TIME; Current_time_rec.hours := 12; 11

PL/SQL basics PL/SQL placeholders DECLARE TYPE T_POPULATION IS TABLE OF NUMBER INDEX BY VARCHAR2(64); l_city_population T_POPULATION; l_i number; BEGIN l_city_population('Smallville') := 2000; l_i:= l_city_population('Smallville') ; END; / 12

PL/SQL basics PL/SQL placeholders DECLARE TYPE T_FOURSOME IS VARRAY(4) OF VARCHAR2(15); l_team T_FOURSOME := T_FOURSOME('John', 'Mary', 'Alberto'); BEGIN l_team.EXTEND; -- Append one null element l_team(4):='Mike';-- Set 5 th element element DBMS_OUTPUT.PUT_LINE( l_team( l_team.first ) ); -- Print first element DBMS_OUTPUT.PUT_LINE( l_team( l_team.last ) ); -- Print last element END; / 13

PL/SQL basics PL/SQL placeholders DECLARE TYPE T_ROSTER IS TABLE OF VARCHAR2(15); l_names T_ROSTER := T_ROSTER('D Caruso', 'J Hamil', 'D Piro', 'R Singh'); l_i number; BEGIN FOR l_i IN l_names.FIRST.. L_names.LAST LOOP --For first to last element DBMS_OUTPUT.PUT_LINE(l_names(l_i)); END LOOP; END; / 14

PL/SQL basics Attributes %TYPE and %ROWTYPE  %TYPE references type of a variable or a database column  %ROWTYPE references type of a record structure, table row or a cursor  Advantages:  an actual type does not need to be known  If referenced type had changed -> will be recompiled automatically 15

PL/SQL basics %TYPE and %ROWTYPE examples balance NUMBER(7,2); minimum_balance balance%TYPE := 10.00; my_dname scott.dept.dname%TYPE; dept_rec dept%ROWTYPE; SELECT deptno, dname, loc INTO dept_rec FROM dept WHERE deptno = 30; variable declarations using record variable to read a row from a table 16

PL/SQL basics PL/SQL Control Structures  Conditional Control  Using IF and CASE statements  Sequential Control  Using GOTO statement DECLARE l_grade CHAR(1) := 'B'; BEGIN CASE l_grade WHEN 'A' THEN DBMS_OUTPUT.PUT_LINE('Excellent'); WHEN 'B' THEN DBMS_OUTPUT.PUT_LINE('Very Good'); WHEN 'C' THEN DBMS_OUTPUT.PUT_LINE('Good'); WHEN 'D' THEN DBMS_OUTPUT.PUT_LINE('Fair'); WHEN 'F' THEN DBMS_OUTPUT.PUT_LINE('Poor'); ELSE DBMS_OUTPUT.PUT_LINE('No such grade'); END CASE; END; DECLARE l_sales NUMBER(8,2) := 20000; l_bonus NUMBER(6,2); BEGIN IF l_sales > THEN l_bonus := 1500; ELSIF l_sales > THEN l_bonus := 500; ELSE l_bonus := 100; END IF; UPDATE employees SET salary = salary + l_bonus; END; 17

PL/SQL basics PL/SQL Control Structures  Iterative loops  Simple loop (infinite)  WHILE loop  FOR loop Numeric range Reversed Cursor based DECLARE l_i NUMBER := 0; BEGIN LOOP DBMS_OUTPUT.PUT_LINE (TO_CHAR(l_i)); l_i:=l_i+1; END LOOP; WHILE l_i < 10 LOOP DBMS_OUTPUT.PUT_LINE (TO_CHAR(l_i)); l_i := l_i + 1; END LOOP; FOR l_i IN LOOP DBMS_OUTPUT.PUT_LINE (TO_CHAR(l_i)); END LOOP; FOR l_i IN REVERSE 1..3 LOOP DBMS_OUTPUT.PUT_LINE (TO_CHAR(l_i)); END LOOP; END; 18

PL/SQL basics PL/SQL Control Structures  Iterative loops  Named loops  Exiting loops  EXIT statement  Loop skipping  CONTINUE DECLARE l_i NUMBER := 0; l_j NUMBER := 0; l_s NUMBER :=0; BEGIN > LOOP l_i := l_i + 1; > LOOP l_j := l_j + 1; l_s := l_s + l_i * l_j; EXIT inner_loop WHEN (l_j > 5); EXIT outer_loop WHEN ((l_i * l_j) > 15); END LOOP inner_loop; DBMS_OUTPUT.PUT_LINE('Sum:'||TO_CHAR(l_s)); IF l_s > 100 THEN EXIT; END IF; END LOOP outer_loop; END; 19

PL/SQL basics Accessing Data in the Database  Selecting at most one row:  SELECT INTO statement  Selecting Multiple rows:  Cursors  Inserting, updating, deleteing (DML) SELECT COUNT(*) INTO variable FROM my_table; SELECT * INTO record FROM my_table WHERE …; INSERT INTO my_table VALUES (var1, var2, …); 20 UPDATE my_table SET col1 = var1, col2= var2 WHERE… ;

PL/SQL basics Cursors EMP_NOEMP_NAMEEMP_JOBEMP_HIREDATEEMP_DEPTNO 380KINGCLERK1-JAN BLAKEANALYST11-JAN CLARKCLERK1-FEB SMITHCLERK2-DEC JONESMANAGER5-JUL SCOTTANALYST20-JUL ADAMSCLERK14-MAR FORDANALYST25-SEP each SQL query produces a result set - cursor set of rows resides on the server in a session’s process memory PL/SQL program can read the result set in iterating fashion Result Set select emp_no,emp_name,emp_job from employees where emp_no > 500; 21

PL/SQL basics Defining explicit cursors  The simplest cursor:  Full cursor syntax  The SQL select statement is static (hardcoded) But can be parameterized (bind variables)  The return type is needed in declarations (packages)  Cursor attributes  %FOUND, %NOTFOUND, %ROWCOUNT, %ISOPEN CURSOR my_cursor IS SELECT * from table; CURSOR name(parameter_list) RETURN rowtype IS SELECT …; 22

PL/SQL basics Using explicit cursors  Fetching results of a query into RECORD DECLARE l_employees employees%ROWTYPE; CURSOR l_c (p_low NUMBER DEFAULT 0, p_high NUMBER DEFAULT 99) is SELECT * FROM employees WHERE job_id > p_low AND job_id < p_high; BEGIN OPEN l_c(3,20); LOOP FETCH l_c INTO l_employees; EXIT WHEN l_c%NOTFOUND; DBMS_OUTPUT.PUT_LINE(l_employees.last_name || l_employees.job_id ); END LOOP; CLOSE l_c; END; / 23

PL/SQL basics Implicit cursor DECLARE l_rows number(5); BEGIN UPDATE employee SET salary = salary ; IF SQL%NOTFOUND THEN dbms_output.put_line('None of the salaries where updated'); ELSIF SQL%FOUND THEN l_rows := SQL%ROWCOUNT; dbms_output.put_line('Salaries for ' || l_rows || 'employees are updated'); END IF; END; 24 BEGIN FOR item IN ( SELECT last_name, job_id FROM employees WHERE job_id LIKE '%CLERK%' AND manager_id > 120 ) LOOP DBMS_OUTPUT.PUT_LINE ( 'Name = ' || item.last_name || ', Job = ' || item.job_id ); END LOOP; END; /

PL/SQL basics Dynamic PL/SQL  PL/SQL code can be generated and called during run time (from a static PL/SQL)  When it is useful  for SQL which text is unknown at compiling time  some objects types cannot be parameterized by using bind variables table name database link …  DDL statements  Be aware of SQL injections  Use dynamic SQL when it is really needed 25

PL/SQL basics Dynamic SQL & PL/SQL  DML  Selecting data from dynamic table_name  Calling a PL/SQL block dynamically L_sql_stmt := 'INSERT INTO payroll VALUES (:x, :x, :y, :x)'; EXECUTE IMMEDIATE ;_sql_stmt USING l_a, l_b; -- using variables EXECUTE IMMEDIATE 'select id form '||l_table_name||' where name=:a ' using l_job_name returning into l_job_id; l_plsql_block := 'BEGIN calc_stats(:x, :x, :y, :x); END;'; EXECUTE IMMEDIATE l_plsql_block USING l_a, l_b; 26

PL/SQL basics PL/SQL Subprograms  Subprogram = named PL/SQL block  schema object = stored in a database  can have parameters  invocation from a named block from an anonymous block recursively  Subprogram types  Procedures complex data processing  Functions frequent, simple operations returns a value can be called from a SQL statement 27

PL/SQL basics PL/SQL Subprograms  Subprogram header specifies:  name of the block and parameter list  return type (function headers)  Subprogram parameters:  Parameter input modes: IN (default) Passes value to that cannot be changed by the subprogram OUT Return value. Should be initialized in the subprogram IN OUT Passes a value and returns updated one by subprogram Any of them can have a default value 28

PL/SQL basics PL/SQL Procedures  Procedure definition  Procedure invocation CREATE OR REPLACE PROCEDURE EXE$RAISE_SALARY ( p_emp_id IN NUMBER, p_amount IN NUMBER ) IS BEGIN UPDATE employees SET salary = salary + p_amount WHERE employee_id = p_emp_id; END EXE$RAISE_SALARY; 29 begin EXE$RAISE_SALARY(20, 1000); end; exec EXE$RAISE_SALARY(l_amount => 1000, l_emp_id => 20); exec EXE$RAISE_SALARY(20, l_amount => 1000);

PL/SQL basics PL/SQL Functions  Function definition  Function invocation CREATE OR REPLACE FUNCTION STF$HALF_OF_SQUARE (p_original NUMBER) RETURN NUMBER IS BEGIN RETURN (p_original * p_original)/2 + (p_original * 4); END STF$HALF_OF_SQUARE; -- inside of a PL/SQL block square INTEGER := STF$HALF_OF_SQUARE(25); -- in a SQL statement select STF$HALF_OF_SQUARE( a ) from squares; 30

PL/SQL basics Subprograms privileges  Creator/owner has full privileges on stored objects  Invoker that is not an owner has to have EXECUTE privilege granted  Granted privileges can be checked in USER_TAB_PRIVS -- USER1 create or replace function my_fuction1 is… grant execute on my_procedure1 to user2; -- USER2 exec user1.myprocedure; 31

PL/SQL basics Subprograms rights  Definer rights (default for named blocks)  Invoker rights  Anonymous blocks have always invoker rights create or replace procedure procedure_name [authid definer] is… create or replace function procedure_name authid current_user is… 32

PL/SQL basics Error Handling  If an error interrupts the execution of the program a n exception is raised  Exception can be handled  by current unit in the exception section or  will be propagated to the enclosing block  After the exception is handled, the control is passed to the enclosing block 33

PL/SQL basics PL/SQL Exceptions  PL/SQL block can define and raise exception  Exceptions can by caught and handled by the user’s code (in exception body)  Exceptions does not automatically rollback or commit changes  Categories of exceptions  Internally defined (without name, just error code)  Predefined (with name and error code)  User-defined (with name, raised always explicitly) 34

PL/SQL basics PL/SQL Exceptions DECLARE l_out_of_stock EXCEPTION; l_number_on_handNUMBER := 0; BEGIN IF l_number_on_hand < 1 THEN RAISE l_out_of_stock; END IF; EXCEPTION WHEN l_out_of_stock THEN DBMS_OUTPUT.PUT_LINE ( 'Encountered out of stock error' ); WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE ( 'Houston we''ve got a problem!' ); END; 35

PL/SQL basics PL/SQL Packages  Schema object  group of logically related PL/SQL items types variables and constants subprograms cursors exceptions  2 parts:  Specification  public interface  Body  private implementation  Packages are global  Cannot be called, parameterized, or nested.  Package state persist for the duration of the database session 36

PL/SQL basics Why use Packages  Modularity  Encapsulation of data and functionality  Clear interface specification independent from the implementation  Easier development  Added functionality:  global variables  global types  Better performance 37

PL/SQL basics Package Specification 1. Header 2. Declarations of global types and variables (public) 3. Declaration of cursors With RETURN clause, but no SELECT statement 4. Declaration of public subprograms (interface) 38

PL/SQL basics Package Specification CREATE OR REPLACE PACKAGE KNL_EMP_ADM AS TYPE T_EMPRECTYP IS RECORD (emp_id NUMBER, sal NUMBER); CURSOR desc_salary RETURN T_EMPRECTYP ; invalid_salary EXCEPTION; PROCEDURE EXE$FIRE_EMPLOYEE (p_emp_id NUMBER); PROCEDURE EXE$RAISE_SALARY (p_emp_id NUMBER,p_amount NUMBER); FUNCTION STF$HIGHEST_SALARY (p_n NUMBER) RETURN T_EMPRECTYP; END KNL_EMP_ADM; / 39

PL/SQL basics Package Body 1. Header 2. Additional declarations of types and variables (private) 3. Specification and SELECT statements of cursors 4. Specification and body of subprograms 5. Initialization code  Executed once when the package is first accessed 40

PL/SQL basics Package Body CREATE OR REPLACE PACKAGE BODY KNL_EMP_ADM AS session_actions_counter NUMBER; CURSOR desc_salary RETURN T_EMPRECTYP IS SELECT employee_id, salary FROM employees ORDER BY salary DESC; PROCEDURE EXE$FIRE_EMPLOYEE (p_emp_id NUMBER) IS BEGIN DELETE FROM employees WHERE employee_id = p_emp_id; END EXE$FIRE_EMPLOYEE; PROCEDURE EXE$RAISE_SALARY (p_emp_id NUMBER,p_amount NUMBER) IS... BEGIN INSERT INTO emp_audit VALUES (SYSDATE, USER, 'EMP_ADMIN'); session_actions_counter := 0; END; END KNL_EMP_ADM; / 41

PL/SQL basics Oracle Supplied Packages  Extend the functionality of the database  Some examples of packages:  DBMS_JOB: for task scheduling  DBMS_PIPE: for communication between sessions  DBMS_OUTPUT: display messages to the session output device  UTL_HTTP: makes HTTP callouts.  Many others… 42

PL/SQL basics Triggers  Stored procedure  Executed automatically when:  data modification (DML Trigger) INSERT, UPDATE, UPDATE column or DELETE  schema modification (DDL Trigger)  system event, user logon/logoff (System Trigger)  Basic DML triggers types:  BEFORE statement  BEFORE each row modification  AFTER each row modification  AFTER statement  INSTEAD OF - to enable data modification by views 43

PL/SQL basics When To Use Triggers  Automatic data generation  Auditing (logging), statistics  Derived data  Data replication  Special referential constrains  Complex logic  Distributed constrains  Time based constrains  Updates of complex views  Triggers may introduce hard to spot interdependencies to a database schema 44

PL/SQL basics Trigger Body  Built like a PL/SQL procedure  Additionally:  Type of the triggering event can be determined inside the trigger using conditional predicators IF inserting THEN … END IF;  Old and new row values are accessible via :old and :new qualifiers (record type variables) 45

PL/SQL basics Trigger Example CREATE OR REPLACE TRIGGER audit_sal BEFORE UPDATE OF salary ON employees FOR EACH ROW BEGIN INSERT INTO emp_audit VALUES( :old.employee_id, SYSDATE, :new.salary, :old.salary ); COMMIT; END; / 46

PL/SQL basics Jobs  Schedule + PL/SQL subprogram  Many scheduling modes  Creation  Using DBMS_SCHEDULER internal package Alternative DBMS_JOB is old and should by avoided  Privileges needed execute on DBMS_SCHEDULER create job 47

PL/SQL basics Jobs example  Daily execution (everyday at 12) of my_saved_procedure BEGIN DBMS_SCHEDULER.CREATE_JOB ( job_name => 'my_new_job1', program_name => 'my_saved_procedure', repeat_interval => 'FREQ=DAILY;BYHOUR=12', comments => 'Daily at noon'); END; / 48

PL/SQL basics Advantages of PL/SQL  Tightly integrated with SQL  Reduced network traffic  Portability - easy deployment and distribution  Data layer separated from client language  Modification without changing of application code  Can be shared by many platform  Server-side periodical data maintenance (jobs) 49

PL/SQL basics References  Oracle Documentation   PL/SQL language reference  2/e25519/toc.htm 2/e25519/toc.htm  PL/SQL packages reference  2/e25788/toc.htm 2/e25788/toc.htm 50