PL/SQL ISYS 464. PL/SQL Block-Structured Variable declaration section Executable section Exception-handling section.

Slides:



Advertisements
Similar presentations
PL/SQL.
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.
INTRODUCTION TO ORACLE Lynnwood Brown System Managers LLC Introduction to PL/SQL – Lecture 6.
PL/SQL Agenda: Basic PL/SQL block structure
Programming in Oracle with PL/SQL
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
Exception Handling in PL/SQL. POINTS TO DISCUSS What is Exception Handling Structure of Exception Handling Section Types of Exceptions.
Structured Query Language. Brief History Developed in early 1970 for relational data model: –Structured English Query Language (SEQUEL) –Implemented with.
Creating Trigger and Maintaining Update Log with PL/SQL ISYS 650.
Bordoloi and Bock PROCEDURES, FUNCTIONS & TRIGGERS.
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.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 2 Basic PL/SQL Block Structures.
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.
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 A BRIEF OVERVIEW DAVID WILSON. PL/SQL User’s Guide and Reference PL/SQL User’s Guide and Reference.
1. 1. Which type of argument passes a value from a procedure to the calling program? A. VARCHAR2 B. BOOLEAN C. OUT D. IN 2.
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
Advanced SQL Instructor: Mohamed Eltabakh 1 Part II.
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:
PL/SQL Procedural Language / Structured Query Language.
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.
1 ISYS Triggers. 2 Agenda Triggers Review Correlation identifiers (pseudo records) Restrictions on triggers Trigger usage Mutating tables Enabling.
PL/SQL Declaring Variables PL/SQL Block Structure DECLARE (Optional) Variables, cursors, user-defined exceptions BEGIN (Mandatory) - SQL statements -
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.
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.
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.
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.
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.
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.
CS422 Principles of Database Systems Oracle PL/SQL Chengyu Sun California State University, Los Angeles.
1 Copyright © 2004, Oracle. All rights reserved. PL/SQL Programming Concepts: Review.
ISYS Triggers.
ITEC 224 Database Programming
A Guide to SQL, Seventh Edition
Difference between Oracle PL/SQL and MySQL
Interacting with the Oracle Server
PL/SQL.
Oracle11g: PL/SQL Programming Chapter 2 Basic PL/SQL Block Structures.
Handling Exceptions.
SQL PL/SQL Presented by: Dr. Samir Tartir
PL/SQL – Session 1 of 4 Instructor: Jim Cody
ISYS Triggers.
Handling Exceptions.
PL/SQL week10.
PL/SQL Declaring Variables.
Presentation transcript:

PL/SQL ISYS 464

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

Printing 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);

Caltax.sql declare taxRate number(3,2); eid emp.empid%type; empSalary emp.salary%type; tax number(7,2); begin taxRate :=&taxRate; select salary into empSalary from emp where empid = '&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; /

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 addorder ( ordid orders.oid%TYPE, custID orders.cid%TYPE, salesID orders.sid%TYPE, orddate orders.odate%TYPE) is tempid customers.cid%TYPE; begin select cid into tempid from customers where cid=custid; insert into orders values(ordid,custid,salesid,orddate); exception when no_data_found then dbms_output.put_line('Customer record not exist'); end; / Note: To run a stored procedure: execute addorder('O8','C1','S3','05-NOV-07');

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

create or replace function emptax(sal emp.salary%type) return number is tax number(6,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 empid, ename, emptax(salary) FROM emp;

Cursors A cursor is a pointer to a set of records returned by a SQL statement. It enables you to take a set of records and deal with it on a row-by-row basis.

Defining and Using Cursors Declare cursor: –CURSOR cursorname IS SQL statement Ex: cursor maleemp is select empid,ename,salary from emp where sex='M'; Open cursor: OPEN maleemp; Fetch data into variables: FETCH maleemp into eid,empname,sal; Use %FOUND to test if record exist CLOSE cursor

declare eid emp.empid%type; empname emp.ename%type; sal emp.salary%type; cursor maleemp is select empid,ename,salary from emp where sex='M'; begin open maleemp; fetch maleemp into eid,empname,sal; while maleemp%found loop dbms_output.put_line(eid || empname || sal); fetch maleemp into eid,empname,sal; end loop; close maleemp; end; / Note: To run a cursor: SQL> Start C:\Empcursor1.sql

Cursor with Arguments declare eid emp.empid%type; empname emp.ename%type; sal emp.salary%type; cursor gender(s emp.sex%type) is select empid,ename,salary from emp where sex=s; begin open gender('&gender'); fetch gender into eid,empname,sal; while gender%found loop dbms_output.put_line(eid || empname || sal); fetch gender into eid,empname,sal; end loop; close gender; end; / Note: ecursor2.sql

declare eid emp.empid%type; empname emp.ename%type; sal emp.salary%type; gender emp.sex%type; bonus number(6,2); cursor e is select empid,ename,salary,sex from emp; begin open e; fetch e into eid,empname,sal,gender; while e%found loop if gender='M' then if sal < 3000 then bonus := sal*.2; else bonus := sal*.1; end if; else if sal < 3000 then bonus:= sal*.25; else bonus:=sal*.15; end if; dbms_output.put_line(eid || empname || sal||gender||bonus); fetch e into eid,empname,sal,gender; end loop; close e; end; / Note: EmpBonusCursor.SQL

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 emp for each row begin dbms_output.put_line(:old.ename || ' 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