Creating Trigger and Maintaining Update Log with PL/SQL ISYS 650.

Slides:



Advertisements
Similar presentations
AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
Advertisements

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.
Oracle PL/SQL (2) John Ortiz. Lecture 14Oracle PL/SQL (2)2 Package  A package is a group of related PL/SQL objects (variables, …), procedures, and functions.
A Guide to Oracle9i1 Advanced SQL And PL/SQL Topics Chapter 9.
PL/SQL Agenda: Basic PL/SQL block structure
Programming in Oracle with PL/SQL
PL/SQL The Oracle Programming Language. Purpose SQL is a non-procedural language. Often we need to put structure on transactions, so we use the supplemental.
A Guide to SQL, Seventh Edition. Objectives Embed SQL commands in PL/SQL programs Retrieve single rows using embedded SQL Update a table using embedded.
Introduction to PL/SQL
Structured Query Language. Brief History Developed in early 1970 for relational data model: –Structured English Query Language (SEQUEL) –Implemented with.
2 Copyright © 2004, Oracle. All rights reserved. Creating Stored Functions.
Bordoloi and Bock PROCEDURES, FUNCTIONS & TRIGGERS.
PL/SQL Introduction Database 1. Practice. Sample Database The schema of the sample database is the following: Drinkers (name, occupation, birthday, salary)
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.
SQL Training Procedures & Functions. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. DB Procedures & Functions Procedures and Functions.
1 Introduction to PL/SQL. 2  Procedural programming language  Uses detailed instructions  Processes statements sequentially  Combines SQL commands.
PL/SQL PL/SQL is Oracle's Procedural Language extension to SQL. PL/SQL has many programming language features. Program units written in PL/SQL can be stored.
Structured Query Language. Brief History Developed in early 1970 for relational data model: –Structured English Query Language (SEQUEL) –Implemented with.
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.
Oracle10g Developer: PL/SQL Programming1 Objectives Programming fundamentals The PL/SQL block Define and declare variables Initialize variables The NOT.
MySQL Stored Procedure and User-Defined Function ISYS 475.
INTRODUCTION TO PL/SQL. Class Agenda Introduction Introduction to PL/SQL Declaring PL/SQL Variable Creating the Executable Section Interacting with the.
1 Copyright © 2004, Oracle. All rights reserved. Introduction to PL/SQL.
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.
PL/SQL ISYS 464. PL/SQL Block-Structured Variable declaration section Executable section Exception-handling section.
PL SQL Block Structures. What is PL SQL A good way to get acquainted with PL/SQL is to look at a sample program. PL/SQL combines the data manipulating.
Advanced SQL: Cursors & Stored Procedures
CS178 Database Management PL/SQL session 8 References: ORACLE 9i PROGRAMMING A Primer Rajshekhar Sunderraman.
PL/SQL Oracle's Database Programming Language. Remember: Set serveroutput on With serveroutput off (default) executing procedure: With serveroutput on:
1 Copyright © 2004, Oracle. All rights reserved. Introduction to PL/SQL.
CIS4368: Advanced DatabaseSlide # 1 PL/SQL Dr. Peeter KirsSpring, 2003 PL/SQL.
Trapping Oracle Server Exceptions. 2 home back first prev next last What Will I Learn? Describe and provide an example of an error defined by the Oracle.
PL/SQL Block Structure DECLARE - Optional Variables, cursors, user-defined exceptions BEGIN - Mandatory SQL Statements PL/SQL Statements EXCEPTIONS - Optional.
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.
Database Management COP4540, SCS, FIU Oracle PL/SQL (Ch 10.5)
Database Technology Jing Shen.
School of Computing and Management Sciences © Sheffield Hallam University SQL is non-procedural –designed to be relatively approachable to non- programmers.
Advanced SQL: Triggers & Assertions
Oracle 8i Exception Handling. General Syntax DECLARE --- BEGIN --- EXCEPTION WHEN exception_name1 THEN -Error handling statements WHEN exception_name2.
Using SQL in PL/SQL ITEC 224 Database Programming.
Chapter 16 Cursors and Exceptions. Chapter Objectives  Determine when an explicit cursor is required  Declare, open, and close an explicit cursor 
A Guide to SQL, Eighth Edition Chapter Eight SQL Functions and Procedures.
DATABASE PROGRAMS CS 260 Database Systems. Overview  Introduction  Anonymous blocks  Oracle’s PL/SQL language basics  Conditions and loops  Cursors.
Creating Functions. V 12 NE - Oracle 2006 Overview of Stored Functions A function is a named PL/SQL block that returns a value A function can be stored.
Handling Exceptions. Objectives What is exception Types of exceptions How to handle exceptions Trapping pre defined oracle errors.
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.
A database trigger is a stored PL/SQL program unit associated with a specific database table. ORACLE executes (fires) a database trigger automatically.
Oracle10g Developer: PL/SQL Programming1 Objectives Named program units How to identify parameters The CREATE PROCEDURE statement Creating a procedure.
Advanced SQL: Cursors & Stored Procedures Instructor: Mohamed Eltabakh 1.
Kingdom of Saudi Arabia Ministry of Higher Education Al-Imam Muhammad Ibn Saud Islamic University College of Computer and Information Sciences Overview.
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 PROCEDURE & STORED FUNCTION Politeknik Telkom 2012.
CS422 Principles of Database Systems Oracle PL/SQL Chengyu Sun California State University, Los Angeles.
ITEC 224 Database Programming
Creating Stored Functions
A Guide to SQL, Seventh Edition
Interacting with the Oracle Server
Interacting with the Oracle Server
PL/SQL.
Handling Exceptions.
Database Management Systems 2
Database Management Systems 2
Handling Exceptions.
PL/SQL week10.
PL/SQL Declaring Variables.
TRIGGERS.
Presentation transcript:

Creating Trigger and Maintaining Update Log with PL/SQL ISYS 650

Introduction to PL/SQL Pl/SQL Block-Structured –Variable declaration section –Executable section –Exception-handling section

Variable Declaration Variable name: begin with a letter and up to 30 characters. Data types: –Character: CHAR(n), VARCHAR2(n) –Number: INTEGER, INT, SMALLINT –DECIMAL(i,j), NUMBER(i,j) –Boolean –Date

Examples DECLARE EidCHAR(3); EnameVARCHAR2(25); HireDateDATE DEFAULT SYSDATE; SalaryNUMBER(7,2); TaxRateNUMBER(4,2) :=5.25;

%TYPE Use a column’s data type as the data type for the variable: –CustomerName Customer.Cname%TYPE;

Executable Section BEGIN –Statements END; / –“/ “ signals the end of program.

Assignment Statement Tax := Salary * TaxRate; Arithemetic operators: –+, -, *, /, ** Concatenation: –|| FullName := (FirstName || ‘ ‘ || LastName);

Substitution Variables &variableName –Ex. &Salary On screen you will see: –Enter value for Salary: Select * from Customer Where CID=‘&CID’; Ex1: Get input from screen: –Salary := &Salary;

SELECT … INTO SELECT columns separated by commas INTO variables separated by commas FROM tablename WHERE condition; Ex1: –SELECT cid, cname INTO custID, customername –FROM customer –WHERE cid = ‘c01’; Ex2: Using substituion variable –SELECT cid, cname INTO custID, customername –FROM customer –WHERE cid = ‘&cid’;

Decisions IF condition THEN –Statements/* each statement ends with ; */ END IF; IF … THEN … ELSE …END IF; IF … THEN ELSIF ……ELSE … END IF;

Loop WHILE condition LOOP –Statements END LOOP; FOR i IN LOOP –Statements END LOOP

Displaying Output SET SERVEROUTPUT ON; DBMS_OUTPUT.PUT_LINE(string to print); –DBMS_OUTPUT is a build in package, PUT_LINE is a procedure in that package. Ex. –Tax:=Salary * TaxRate; –DBMS_OUTPUT.PUT_LINE(‘Your tax is: ‘ || Tax);

Script: Caltax.sql declare taxRate number(3,2); eid employees.employee_id%type; empSalary employees.salary%type; tax number(7,2); begin taxRate :=&taxRate; select salary into empSalary from employees where employee_id = '&eid'; tax := empSalary * taxRate; dbms_output.put_line('Tax is : ' || tax); end; /

Exceptions Exceptions are errors. Predefined exceptions: –No_Data_Found: Select statement returns no row. –Too_Many_Rows: Single-Row Select statement returns more than one row. –Value_Error:Data conversion errors.

Handling Exceptions Exception –WHEN exceptionname THEN –Statements –WHEN OTHERS THEN –Statements Ex: PLSQLException.SQL Declare CustName Customer.Cname%Type; begin select Cname into Custname from customer where cid='&CID'; dbms_output.put_line('Customer name is : ' || Custname); exception when no_data_found then dbms_output.put_line('Customer record not exist'); end; /

Functions CREATE [OR REPLACE] FUNCTION functionname IS [Variable declarations] BEGIN Statements RETURN expression; END; /

create or replace function emptax(sal employees.salary%type) return number is tax number(8,2); begin if sal < then tax:=sal*0.1; elsif sal < then tax:=sal*0.2; else tax:=sal*0.3; end if; return tax; end; /

Using the User-defined Function with SQL Select employee_id,first_name || ' ' || last_name as Ename, empTax(Salary) as Tax FROM employees;

Creating Stored Procedure A procedure is a named program block: CREATE [OR REPLACE] PROCEDURE procedurename IS [Variable declarations] BEGIN Statements END; / Note: To run a procedure: EXECUTE procedurename

create or replace procedure addCustomer ( custid customer.cid%TYPE, cname customer.cname%TYPE, city customer.city%TYPE, rating customer.rating%TYPE) is tempid customer.cid%TYPE; begin select cid into tempid from customer where cid=custid; dbms_output.put_line('Customer record already exist'); exception when no_data_found then insert into customer values(custid,cname,city,rating); end; / Note: To run a stored procedure: execute addcustomer('C12','Mia','LA','C');

Create a procedure to Issue Refresh Command create or replace procedure RefreshMVCust as begin DBMS_MVIEW.REFRESH('MVCustomer'); end; / Note: A stored procedure can be called from an application.

Triggers A trigger is a program stored in the database and is called automatically when a triggering event occurs. Update events: –Insert, Delete, Update BEFORE Insert|Delete|Update ON tablename AFTER Insert|Delete|Update ON tablename Accessing new value and old value: –:NEW.fieldname –:OLD.fieldname FOR EACH ROW

Demo :New and :Old create or replace trigger changesal after update on employees for each row begin dbms_output.put_line(:old.Last_name || ' old salary is:' || :old.salary); dbms_output.put_line('new salary is: ' || :new.salary); end; / Note: EmpSaltrigger.sql

create or replace trigger adddetail before insert on orderdetail for each row declare stocks product.onhand%type; begin select onhand into stocks from hproduct where pid=:new.pid; if stocks < :new.qty then update product set onhand=0 where pid = :new.pid; dbms_output.put_line('not enough stock'); else update product set onhand=onhand - :new.qty where pid=:new.pid; end if; end; / Note: AddDetailTrigger.sql

Master Table and User-Defined Log

Log Maintenance Log structure: –Record’s fields + Update Time + Update Flag Update Flags: –Deletion: D –Insertion: I –Modification is treated as deletion of the old record with slightly smaller update time and insert of the new record.

Code for Update (Modification) CREATE OR REPLACE TRIGGER "UpdateCustTrigger" after Update on Customer for each row declare UpdTimeStamp CustLog.updatetime%type; begin UpdTimeStamp:=sysdate ; insert into CustLog values(:old.cid,:old.Cname,:old.City,:old.Rating,UpdTimeStamp,'D'); UpdTimeStamp:=sysdate; insert into CustLog values(:new.cid,:new.Cname,:new.City,:new.Rating,UpdTimeStamp,'I') ; end; /

Code for Insertion CREATE OR REPLACE TRIGGER "InsertCustTrigger" after Insert on Customer for each row declare UpdTimeStamp CustLog.updtime%type; begin UpdTimeStamp:=sysdate; insert into CustLog values(:new.cid,:new.Cname,:new.City,:new.Rating,UpdTi meStamp,'I'); end; /

Code for Deletion CREATE OR REPLACE TRIGGER "DeleteCustTrigger" after Delete on Customer for each row declare UpdTimeStamp CustLog.updtime%type; begin UpdTimeStamp:=sysdate; insert into CustLog values(:old.cid,:old.Cname,:old.City,:old.Rating,UpdTimeSta mp,'D'); end; /

Patterns of Update Flag for an Updated Record D, {I, D}: Deletion of an record I, {D, I}: A new record {D, I}: Modification {I, D}: A new record eventually deleted (No impact to MV)

To Select All Deletions from the Log select * from custlog c where updateFlag='D' and updateTime=(select max(updateTime)from custLog where cid=c.cid); Note: For an updated record, select the last entry (the entry with Max(updateTime)) in the log with a Flag of D

To Select All Insertions from the Log select * from custlog c where updateFlag='I' and updateTime=(select max(updateTime)from custLog where cid=c.cid); Note: For an updated record, select the last entry (the entry with Max(updateTime)) in the log with a Flag of I

Demo: Remotely call a stored procedure to refresh a MV Dim strConn As String = "Provider=MSDAORA;Data Source=XE;User ID=dchao;password=???" Dim objConn As New OleDbConnection(strConn) Dim objcomm As New OleDbCommand("RefreshMVCust", objConn) objcomm.CommandType = CommandType.StoredProcedure objConn.Open() objcomm.ExecuteNonQuery() objConn.Close()