PL/SQL.

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 (Procedural Language extensions to SQL) Prepared by: Manoj Kathpalia Edited by: M V Ramakrishna.
Chapter 4B: More Advanced PL/SQL Programming
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
Stored Procedures PL/SQL code stored in the database and executed when called by the user. Called by procedure name from another PL/SQL block or using.
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.
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.
Distributed Database Applications COSC 5050 Week Three.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
1 Introduction to PL/SQL. 2  Procedural programming language  Uses detailed instructions  Processes statements sequentially  Combines SQL commands.
Oracle10g Developer: PL/SQL Programming1 Objectives Manipulating data with cursors Managing errors with exception handlers Addressing exception-handling.
Chapter 4 Cursors and Exception Handling Oracle10g Developer:
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.
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 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
PL/SQL Oracle's Database Programming Language. Remember: Set serveroutput on With serveroutput off (default) executing procedure: With serveroutput on:
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.
BIS Database Systems School of Management, Business Information Systems, Assumption University A.Thanop Somprasong Chapter # 8 Advanced SQL.
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.
PL/SQL Declaring Variables PL/SQL Block Structure DECLARE (Optional) Variables, cursors, user-defined exceptions BEGIN (Mandatory) - SQL statements -
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.
Database Management COP4540, SCS, FIU Oracle PL/SQL (Ch 10.5)
Database Technology Jing Shen.
Commercial RDBMSs Access and Oracle. Access DBMS Architchecture  Can be used as a standalone system on a single PC: -JET Engine -Microsoft Data Engine.
School of Computing and Management Sciences © Sheffield Hallam University SQL is non-procedural –designed to be relatively approachable to non- programmers.
Copyright  Oracle Corporation, All rights reserved. 16 Declaring Variables.
Objectives Database triggers and syntax
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
PL/SQLPL/SQL Oracle11g: PL/SQL Programming Chapter 4 Cursors and Exception Handling.
ITEC 224 Database Programming PL/SQL Lab Cursors.
Oracle10g Developer: PL/SQL Programming1 Objectives SQL queries within PL/SQL Host or bind variables The %TYPE attribute Include queries and control structures.
Introduction to Explicit Cursors. 2 home back first prev next last What Will I Learn? Distinguish between an implicit and an explicit cursor Describe.
A Guide to SQL, Eighth Edition Chapter Eight SQL Functions and Procedures.
PL/SQLPL/SQL Oracle11g: PL/SQL Programming Chapter 9 Database Triggers.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
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.
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.
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,
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.
CS422 Principles of Database Systems Oracle PL/SQL Chengyu Sun California State University, Los Angeles.
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe.
CS422 Principles of Database Systems Stored Procedures and Triggers Chengyu Sun California State University, Los Angeles.
1 Copyright © 2004, Oracle. All rights reserved. PL/SQL Programming Concepts: Review.
Interacting with the Oracle Server
PL/SQL.
SQL PL/SQL Presented by: Dr. Samir Tartir
Chapter 4: Introduction to PL/SQL
Chapter 2 Handling Data in PL/SQL Blocks Oracle9i Developer:
PL/SQL week10.
Procedural Language/Structured Query Language PL/SQL
Oracle9i Developer: PL/SQL Programming Chapter 8 Database Triggers.
Chapter 8 Advanced SQL.
PL/SQL Declaring Variables.
Chapter 8 Advanced SQL Pearson Education © 2009.
Procedural Language/Structured Query Language PL/SQL
Presentation transcript:

PL/SQL

What is PL/SQL Procedural Language – SQL An extension to SQL with design features of programming languages (procedural and object oriented) PL/SQL and Java are both supported as internal host languages within Oracle products.

Why PL/SQL Acts as host language for stored procedures and triggers. Provides the ability to add middle tier business logic to client/server applications. Provides Portability of code from one environment to another Improves performance of multi-query transactions. Provides error handling

PL/SQL BLOCK STRUCTURE DECLARE (optional) - variable declarations BEGIN (required) - SQL statements - PL/SQL statements or sub-blocks EXCEPTION (optional) - actions to perform when errors occur END; (required)

PL/SQL Block Types Anonymous Procedure Function DECLARE BEGIN -statements EXCEPTION END; Procedure PROCEDURE <name> IS BEGIN -statements EXCEPTION END; Function FUNCTION <name> RETURN <datatype> IS BEGIN -statements EXCEPTION END;

PL/SQL Variable Types Scalar (char, varchar2, number, date, etc) Composite (%rowtype) Reference (pointers) LOB (large objects) Note: Non PL/SQL variables include bind variables, host (“global”) variables, and parameters.

Variable Naming Conventions Two variables can have the same name if they are in different blocks (bad idea) The variable name should not be the same as any table column names used in the block.

PL/SQL is strongly typed All variables must be declared before their use. The assignment statement : = is not the same as the equality operator = All statements end with a ;

PL/SQL Sample Program Variable g_inv_value number DECLARE v_price number(8,2) := 10.25; v_quantity number(8,0) := 400; BEGIN :g_inv_value := v_price * v_quantity; END; / Print g_inv_value

PL/SQL Sample Program Set serveroutput on DECLARE v_inv_value number(10,2); v_price number(8,2) := 10.25; v_quantity number(8,0) := 400; BEGIN v_inv_value := v_price * v_quantity; dbms_output.put('The value is: '); dbms_output.put_line(v_inv_value); END; /

PL/SQL Sample Program (with user input) Set serveroutput on Accept p_price Prompt 'Enter the Price: ' DECLARE v_inv_value number(8,2); v_price number(8,2); v_quantity number(8,0) := 400; BEGIN v_price := &p_price; v_inv_value := v_price * v_quantity; dbms_output.put_line('******'); dbms_output.put_line('price * quantity='); dbms_output.put_line(v_inv_value); END; / Note: PL/SQL not designed for user interface programming

PL/SQL Comments DECLARE v_salary number(9,2) := 40000; BEGIN /* this is a multi-line comment that will be ignored by the pl/sql interpreter */ v_salary := v_salary * 2; -- nice raise END; -- end of program

SELECT INTO SET SERVEROUTPUT ON DECLARE v_max_gpa number(3,2); v_numstudents number(4); v_lname students.lname%type; v_major students.major%type; BEGIN select max(gpa) into v_max_gpa from students; DBMS_OUTPUT.PUT_LINE ('The highest GPA is '||v_max_gpa); select count(sid) into v_numstudents from students where gpa = v_max_gpa; IF v_numstudents > 1 then DBMS_OUTPUT.PUT_LINE ('There are '||v_numstudents||' with that GPA'); ELSE select lname, major into v_lname, v_major where gpa=v_max_gpa; DBMS_OUTPUT.PUT_LINE ('The student name is '||v_lname); DBMS_OUTPUT.PUT_LINE ('The student major is '||v_major); END IF; END; /

COMMON PL/SQL STRING FUNCTIONS CHR(asciivalue) ASCII(string) LOWER(string) SUBSTR(string,start,substrlength) LTRIM(string) RTRIM(string) LPAD(string_to_be_padded, spaces_to_pad, |string_to_pad_with|) RPAD(string_to_be_padded, spaces_to_pad, |string_to_pad_with|) REPLACE(string, searchstring, replacestring) UPPER(string) INITCAP(string) LENGTH(string)

COMMON PL/SQL NUMERIC FUNCTIONS ABS(value) ROUND(value, precision) MOD(value,divisor) SQRT(value) TRUNC(value,|precision|) LEAST(exp1, exp2…) GREATEST(exp1, exp2…)

%ROWTYPE Set serveroutput on DECLARE v_student students%rowtype; BEGIN select * into v_student from students where sid='123456'; DBMS_OUTPUT.PUT_LINE (v_student.lname); DBMS_OUTPUT.PUT_LINE (v_student.major); DBMS_OUTPUT.PUT_LINE (v_student.gpa); END; /

CURSORS A cursor is a private set of records An Oracle Cursor = VB recordset = JDBC ResultSet Implicit cursors are created for every query made in Oracle Explicit cursors can be declared by a programmer within PL/SQL.

Cursor Attributes cursorname%ROWCOUNT Rows returned so far cursorname%FOUND One or more rows retrieved cursorname%NOTFOUND No rows found Cursorname%ISOPEN Is the cursor open

Explicit Cursor Control Declare the cursor Open the cursor Fetch a row Test for end of cursor Close the cursor Note: there is a FOR LOOP available with an implicit fetch

Sample Cursor Program DECLARE CURSOR students_cursor IS SELECT * from students; v_student students_cursor%rowtype; /* instead we could do v_student students%rowtype */ BEGIN DBMS_OUTPUT.PUT_LINE ('******************'); OPEN students_cursor; FETCH students_cursor into v_student; WHILE students_cursor%found LOOP DBMS_OUTPUT.PUT_LINE (v_student.last); DBMS_OUTPUT.PUT_LINE (v_student.major); END LOOP; CLOSE students_cursor; END; /

Sample Cursor Program (same program without composite variable) DECLARE CURSOR students_cursor IS SELECT last, major from students; v_Last students.last%type; v_major students.major%type; BEGIN DBMS_OUTPUT.PUT_LINE ('******************'); OPEN students_cursor; FETCH students_cursor into v_last, v_major; WHILE students_cursor%found LOOP DBMS_OUTPUT.PUT_LINE (v_last); DBMS_OUTPUT.PUT_LINE (v_major); END LOOP; CLOSE students_cursor; END; /

When is PL/SQL handy When something is too complicated for SQL When conditional branching and looping are needed Example Write a PL/SQL program that assigns email address to each employee or student in a table. Following these rules: - email address should be all lower case - email address should default to first initial plus the first seven letters of the last name - email can be no longer than eight characters - if email is already used than use first initial plus middle initial plus first six letters of last name - if the previous address is taken use the first two letters of the first name and the first six letters of the last name. - if the previous address is taken use first six letters of last name + 01 or 02 …etc

Stored Procedures PL/SQL code stored in the database and executed when called by the user. Called by procedure name from another PL/SQL block or using EXECUTE from SQL+. For example EXEC SQR(50) Example: Create procedure SQR (v_num_to_square IN number) AS v_answer number(10); BEGIN v_answer := v_num_to_square * v_num_to_square; dbms_output.put_line(v_answer); END; /

Function PL/SQL user defined function stored in the database and executed when a function call is made in code: example x := SQUARED(50) Example: Create or Replace Function SQUARED (p_number_to_square IN number) RETURN number IS v_answer number(10); BEGIN v_answer := p_number_to_square * p_number_to_square; RETURN(v_answer); END; /

Another Stored Procedure Example Create or replace procedure mytabs AS CURSOR table_cursor IS Select table_name from user_tables; v_tablename varchar2(30); BEGIN open table_cursor; fetch table_cursor into v_tablename; while table_cursor%found loop dbms_output.put_line(v_tablename); end loop; close table_cursor; END;

Triggers PL/SQL code executed automatically in response to a database event, typically DML. Like other stored procedures, triggers are stored in the database. Often used to: enforce complex constraints, especially multi-table constraints. Financial posting is an example of this. Trigger related actions implement auditing “logs” pop a sequence when creating token keys Triggers do not issue transaction control statements (such as commit). Triggers are part of the SQL transaction that invoked them. USER_TRIGGERS provides a data dictionary view of triggers.

Triggers CREATE OR REPLACE TRIGGER <trigger_name> [BEFORE/AFTER][DELETE/INSERT/UPDATE of <column_name |, column_name… |> ON <table_name> |FOR EACH ROW| |WHEN <triggering condition>| |DECLARE| BEGIN trigger statements ………… END; To delete a trigger use: DROP TRIGGER <trigger_name>;

Log Trigger Example CREATE OR REPLACE TRIGGER LOGSTUDENTCHANGES BEFORE INSERT OR DELETE OR UPDATE of Major ON STUDENTS FOR EACH ROW DECLARE v_ChangeType CHAR(1); v_sid varchar2(10); BEGIN IF INSERTING THEN V_ChangeType := 'I'; v_sid := :new.sid; ELSIF UPDATING THEN V_ChangeType := 'U'; ELSE V_ChangeType := 'D'; v_sid := :old.sid; END IF; INSERT INTO MAJ_AUDIT (change_type, changed_by, timestamp, SID, old_major, new_major) VALUES (v_ChangeType, USER, SYSDATE, v_sid, :old.major, :new.major); END LOGSTUDENTCHANGES;

UpperCase Trigger Example CREATE OR REPLACE TRIGGER UPPERCASE BEFORE INSERT OR UPDATE ON STUDENTS FOR EACH ROW DECLARE BEGIN :new.lastname:=UPPER(:new.lastname); :new.firstname:=UPPER(:new.firstname); END UPPERCASE; /

Ben & Jerry Trigger Example (no employee can make more than 10 times as much as the lowest paid employee) CREATE OR REPLACE TRIGGER SalaryTrig BEFORE INSERT ON Employees FOR EACH ROW DECLARE v_upper_sal_limit NUMBER(10,2); v_lower_sal_limit NUMBER(10,2); BEGIN SELECT MIN(salary)*10 INTO v_upper_sal_limit FROM employees; SELECT MAX(salary)/10 INTO v_lower_sal_limit IF :new.salary NOT BETWEEN v_lower_sal_limit AND v_upper_sal_limit THEN RAISE_APPLICATION_ERROR(-20001,'salary out of allowed range'); END IF; END SalaryTrig; / Notes: Application error number is a parameter between –20,000 and –20,999. You could also stop the insert by "poisoning" it, changing a :new buffer value to one that you know will not pass constraint evaluation.

SEQUENCE CREATE SEQUENCE <sequence_name> |INCREMENT BY <number>| |START WITH <start_value>| |MAXVALUE <maximum_value>|NOMAXVALUE| |MINVALUE <minimum_value>| |CYCLE|NOCYLE| |CACHE <number of values>|NOCACHE| |ORDER|NOORDER| To pop the next sequence use: SEQUENCENAME.NEXTVAL (CURRVAL shows last pop)