CS422 Principles of Database Systems Oracle PL/SQL Chengyu Sun California State University, Los Angeles.

Slides:



Advertisements
Similar presentations
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.
Advertisements

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.
PL/SQL.
Murali Mani Persistent Stored Modules (Stored Procedures) : PSM.
PL/SQL (Procedural Language extensions to SQL) Prepared by: Manoj Kathpalia Edited by: M V Ramakrishna.
Lecture-5 Though SQL is the natural language of the DBA, it suffers from various inherent disadvantages, when used as a conventional programming language.
Cursors How to step through the returned set of rows.
Chapter 4B: More Advanced PL/SQL Programming
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.
Introduction to PL/SQL
Introduction to PL/SQL Lecture 0 – Self Study Akhtar Ali.
Objectives Why PL-SQL ? Language features
PL/SQL Introduction Database 1. Practice. Sample Database The schema of the sample database is the following: Drinkers (name, occupation, birthday, salary)
Cursors in Pl/SQL 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.
Introduction to PL/SQL. Procedural Language extension for SQL Oracle Proprietary 3GL Capabilities Integration of SQL Portable within Oracle data bases.
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.
SQL enables us to create, organize, retrieve and maintain data stored in database it does not provide the features which a typical programming language.
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.
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.
Chapter 4: 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.
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.
8 1 Chapter 8 Advanced SQL Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
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.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
PL/SQL. Introduction to PL/SQL block Declare declarations Begin executable statement Exception exception handlers End;
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)
1 PL/SQLPL/SQL Declaring Variables Declaring Variables Declaring Variables Declaring Variables Writing Executable Statements Writing Executable Statements.
Copyright  Oracle Corporation, All rights reserved. 16 Declaring Variables.
Oracle 8i Exception Handling. General Syntax DECLARE --- BEGIN --- EXCEPTION WHEN exception_name1 THEN -Error handling statements WHEN exception_name2.
Stored Procedures. Definition a stored procedure is a set of Structured Query Language (SQL) statements with an assigned name that's stored in the database.
Chapter 16 Cursors and Exceptions. Chapter Objectives  Determine when an explicit cursor is required  Declare, open, and close an explicit cursor 
Cursors For viewing and updating. Cursors How to step through the returned set of rows.
DATABASE PROGRAMS CS 260 Database Systems. Overview  Introduction  Anonymous blocks  Oracle’s PL/SQL language basics  Conditions and loops  Cursors.
implicit and an explicit cursor
Program with PL/SQL Lesson 3. Interacting with the Oracle Server.
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.
1 Introduction to Database Systems, CS420 SQL Persistent Stored Modules (PSM) – Stored Procedure.
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.
Pl/SQL LANGUAGE MULITPLE CHOICE QUESTION SET-3
PL/SQL.
Database Programming PL SQL.
SQL PL/SQL Presented by: Dr. Samir Tartir
Agenda Summary of last class Cursors Loops Records Simple Loops
Stored Procedure used in PosgreSQL
Chapter 4: Introduction to PL/SQL
PL/SQL week10.
PL/SQL Declaring Variables.
Presentation transcript:

CS422 Principles of Database Systems Oracle PL/SQL Chengyu Sun California State University, Los Angeles

Limitations of SQL Most programming language are Turing-complete SQL is not

PSM and PL Persistent Stored Modules (PSM) Commonly known as Stored Procedures Stored in the database just like other schema objects Procedural Languages (PL) Programming language for writing stored procedures Based on SQL, Java, C#, Perl, Python, …

Oracle PL/SQL SQL + things you would expect from a conventional programming language: Variables and types Control flow statements Procedures and functions Packages No just for creating stored procedures e.g. can be used like other SQL statements on/oracle/appdev.102/b14261/toc.htm

Example: Hello World NOTE: the slash (/) at the end execute the PL/SQL code /** A simple PL/SQL example */ begin -- print out “Hello World!” dbms_output.put_line( 'Hello World!' ); end; /

Comments C-style comments: /* comments */ SQL-style comments: -- comments

Output DBMS_OUTPUT is one of the built-in packages in Oracle PUT_LINE() Display the content of the output buffer in SQL*Plus SET SERVEROUTPUT ON

Block Structure [DECLARE declaration_statements] BEGIN executable_statements [EXCEPTION exception_handling_statements] END;

Example: Sum NOTE: Be careful with SQL keywords declare a integer := 10; b integer default 2; s integer; begin b := 5; s := a + b; dbms_output.put_line( 'sum is ' || s ); end;

Variable Types All SQL types Some PL/SQL types boolean : true, false, or null string : same as varchar2 record : composite type cursor Collection and object types

TYPE and ROWTYPE price items.price%type; Type of a table column: Type of a table row: item items%rowtype;

Operators Assignment := Arithmetic +,-,*,/,mod Comparison = >,>=,<,<= !=, <>, ^=, ~= Logical AND, OR, NOT Concatenation || SQL LIKE, IS NULL IN, BETWEEN…AND All functions

Example: Price Cap declare l_price items.price%type; begin select max(price) into l_price from items; if l_price <= 9.99 then dbms_output.put_line( ' highest price is ' || l_price); else update items set price = 9.99 where price > 9.99; dbms_output.put_line( 'price capped at 9.99.' ); end if; end;

Naming Conventions We want to avoid using the same names for variables and table columns A simple naming convention: Prefix local variable with l_ Prefix package global variable with g_ Prefix parameters with p_

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;

CASE Statement Note the difference between CASE Statement and CASE Expression. CASE expression WHEN value1 THEN statements [WHEN value2 THEN statements] [ELSE statements] END CASE; CASE WHEN condition1 THEN statements [WHEN constition2 THEN statements] [ELSE statements] END CASE;

Example – Factorial declare n integer ; factorial integer := 1; i integer := 1; begin n := 5; while i <= n loop factorial := factorial * i; i := i+1; end loop; dbms_output.put_line( n || '! = ' || factorial ); end;

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;

Cursors An iterator of a collection of tuples We can use a cursor to process the rows returned by a SELECT statement

Cursors An iterator of a collection of tuples We can use a cursor to process the rows returned by a SELECT statement

Cursors An iterator of a collection of tuples We can use a cursor to process the rows returned by a SELECT statement

Cursors An iterator of a collection of tuples We can use a cursor to process the rows returned by a SELECT statement

Cursors An iterator of a collection of tuples We can use a cursor to process the rows returned by a SELECT statement

Cursors An iterator of a collection of tuples We can use a cursor to process the rows returned by a SELECT statement

Cursors An iterator of a collection of tuples We can use a cursor to process the rows returned by a SELECT statement

Cursors An iterator of a collection of tuples We can use a cursor to process the rows returned by a SELECT statement

Example: Random Output declare l_namestring(32); l_pricenumber; cursor c is select name, price from items; begin open c; fetch c into l_name, l_price; while c%found loop if dbms_random.random > 0 then dbms_output.put_line( l_name || ' ' || l_price ); end if; fetch c into l_name, l_price; end loop; close c; end;

Using Cursors Declaration OPEN FETCH CLOSE

Attributes PL/SQL objects like tables,rows, columns, and cursors have attributes associated with them. Attributes can be access with the % operator. Some useful attributes: Column attributes: %TYPE Table attributes: %ROWTYPE Cursor attributes: %FOUND, %NOTFOUND

Cursor FOR Loop FOR record_name IN cursor_name LOOP statements END LOOP;

Cursors with Parameters declare … cursor c (p_min_price number, p_max_price number) is select name, price from items where price >= p_min_price and price <= p_max_price; begin …. open c (1.99, 19.99); close c; … open c (99.99, ); close c; … end;

Generate Random Number and Strings Random numbers dbms_random.random() dbms_random.value() dbms_random.value(low, high) Random strings dbms_random.string(‘U’, length) dbms_random.string(‘L’, length) dbms_random.string(‘A’, length)

Example: Exception NOTE: the program does not resume after an exception is handled. declare l_price items.price%type; begin select price into l_price from items; dbms_output.put_line( l_price ); exception when too_many_rows then dbms_output.put_line( 'there are too many prices.' ); end;

System Exceptions Some predefined system exceptions: TOO_MANY_ROWS ZERO_DIVIDE INVALID_NUMBER SELF_IS_NULL SUBSCRIPT_OUTSIDE_LIMIT LOGIN_DENIED … OTHERS  Error code is stored in SQLCODE

User Defined Exception DECLARE exception_name EXCEPTION; BEGIN IF condition THEN RAISE exception_name; END IF; EXCEPTION WHEN exception_name THEN statements END;

About PL/SQL Programming It’s just programming like you always do Bring out your CS201 textbook and do some exercises with PL/SQL 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 a cursor to iterate through all tuples