1 Introduction to PL/SQL. 2  Procedural programming language  Uses detailed instructions  Processes statements sequentially  Combines SQL commands.

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.
PL/SQL.
Introduction to C Programming
Lecture-5 Though SQL is the natural language of the DBA, it suffers from various inherent disadvantages, when used as a conventional programming language.
Chapter 4B: More Advanced PL/SQL Programming
Chapter 4: Introduction to PL/SQL. 2 Lesson A Objectives After completing this lesson, you should be able to: Describe the fundamentals of the PL/SQL.
A Guide to Oracle9i1 Advanced SQL And PL/SQL Topics Chapter 9.
PL/SQL Agenda: Basic PL/SQL block structure
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.
Introduction to 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.
Oracle10g Developer: PL/SQL Programming1 Objectives Manipulating data with cursors Managing errors with exception handlers Addressing exception-handling.
PL/SQL Anonymous Blocks
SQL enables us to create, organize, retrieve and maintain data stored in database it does not provide the features which a typical programming language.
Chapter 7 Advanced SQL Database Systems: Design, Implementation, and Management, Sixth Edition, Rob and Coronel.
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.
Chapter 10 Selected Single-Row Functions Oracle 10g: SQL.
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.
Chapter 4: Introduction to PL/SQL
Overview · What is PL/SQL · Advantages of PL/SQL · Basic Structure of a PL/SQL Block · Procedure · Function · Anonymous Block · Types of Block · Declaring.
Oracle 11g: SQL Chapter 10 Selected Single-Row Functions.
LECTURE 1 INTRODUCTION TO PL/SQL Tasneem Ghnaimat.
CS178 Database Management PL/SQL session 8 References: ORACLE 9i PROGRAMMING A Primer Rajshekhar Sunderraman.
Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded.
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.
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.
1 PL/SQLPL/SQL Declaring Variables Declaring Variables Declaring Variables Declaring Variables Writing Executable Statements Writing Executable Statements.
Using SQL in PL/SQL ITEC 224 Database Programming.
Chapter 8 Advanced SQL Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Chapter 9: Advanced SQL and PL/SQL Guide to Oracle 10g.
1 Handling Exceptions Part F. 2 Handling Exceptions with PL/SQL What is an exception? Identifier in PL/SQL that is raised during execution What is an.
Chapter 16 Cursors and Exceptions. Chapter Objectives  Determine when an explicit cursor is required  Declare, open, and close an explicit cursor 
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.
DATABASE PROGRAMS CS 260 Database Systems. Overview  Introduction  Anonymous blocks  Oracle’s PL/SQL language basics  Conditions and loops  Cursors.
1 ITBIS373 Database Development Lecture 2 – Chapter 4B Introduction to PL/SQL.
1 Stored Procedures in MySQL Part I. 2 Objectives SQL Vs. MySQL SP MySQL SP Parameters MySQL SP Control Structures.
Introduction to PL/SQL Francis Thottungal. The outline The basic PL/SQL code structure is : DECLARE -- optional, which declares and define variables,
Kingdom of Saudi Arabia Ministry of Higher Education Al-Imam Muhammad Ibn Saud Islamic University College of Computer and Information Sciences Overview.
Slide 1 Chapter 3 Variables  A variable is a name for a value stored in memory.  Variables are used in programs so that values can be represented with.
CS422 Principles of Database Systems Oracle PL/SQL Chengyu Sun California State University, Los Angeles.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
1 Copyright © 2004, Oracle. All rights reserved. PL/SQL Programming Concepts: Review.
Pl/SQL LANGUAGE MULITPLE CHOICE QUESTION SET-3
A Guide to SQL, Seventh Edition
PL/SQL.
Oracle11g: PL/SQL Programming Chapter 2 Basic PL/SQL Block Structures.
Topics Introduction to File Input and Output
Introduction to C++ Programming
Chapter 4: Introduction to PL/SQL
Chapter 2 Handling Data in PL/SQL Blocks Oracle9i Developer:
PL/SQL week10.
Chapter 8 Advanced SQL.
Topics Introduction to File Input and Output
Presentation transcript:

1 Introduction to PL/SQL

2  Procedural programming language  Uses detailed instructions  Processes statements sequentially  Combines SQL commands with procedural instructions  Used to perform sequential processing using an Oracle database What is PL/SQL?

3 PL/SQL Variables Variable names must follow the Oracle naming standard Can use reserved words (BEGIN, NUMBER) and table names for variable names, but is not a good practice Make variable names descriptive Use lower-case letters, and separate words with underscores Example: current_s_id

4 Declaring PL/SQL Variables PL/SQL is a strongly-typed language All variables must be declared prior to use Syntax for declaring a variable: variable_name data_type_declaration; Example: current_s_id NUMBER(6);

5 PL/SQL Data Types Scalar References a single value Composite References a data structure Reference References a specific database item LOB References a large binary object

6 Scalar Data Types Database scalar data types: VARCHAR2 CHAR DATE LONG NUMBER Non-database scalar data types: Integers: BINARY_INTEGER, INTEGER, INT, SMALLINT Decimal numbers: DEC, DECIMAL, DOUBLE, PRECISION, NUMERIC, REAL BOOLEAN

7 Composite Data Types Reference multiple data elements, such as a record Types: RECORD TABLE VARRAY Tabular structure that can expand or contract as needed

8 Reference Data Types Reference a database item Assume data type of item %TYPE: assumes data type of field %ROWTYPE: assumes data type of entire row

9 DECLARE Variable declarations BEGIN Program statements EXCEPTION Error-handling statements END; Body Variable Declarations Exception Section Exception Section PL/SQL Program Structure

10  May span multiple text editor lines  Each line ends with a semicolon  Text is not case sensitive PL/SQL Program Lines

11  Block of comments are delimited with /* */ /* */  Single comment line starts with 2 hyphens -- comment on a single line Comment Statements

12 ExampleResult Arithmetic Operators

13  Assignment operator: :=  Variable being assigned to a new value is on left side of assignment operator  New value is on right side of operator student_name := ‘John Miller’; student_name := current_student; Assignment Statements

14  Normally PL/SQL is used with other Oracle utilities such as forms or reports  You will learn to use PL/SQL in SQL*Plus  Command to activate memory buffer in SQL*Plus to enable output from PL/SQL programs: SQL> SET SERVEROUTPUT ON SIZE buffer_size; SQL> SET SERVEROUTPUT ON SIZE 4000; Displaying PL/SQL Output in SQL*Plus

15  Command to output data from a PL/SQL program in SQL*Plus: DBMS_OUTPUT.PUT_LINE(‘output string’); DBMS_OUTPUT.PUT_LINE(‘Current Output:’); Displaying PL/SQL Program Output in SQL*Plus

16  Copy program code from Notepad to SQL*Plus  Type / to execute Executing a PL/SQL Program in SQL*Plus

17  TO_DATE: character string to DATE TO_DATE(‘07/14/01’, ‘MM/DD/YY’);  TO_NUMBER: character string to NUMBER TO_NUMBER(‘2’);  TO_CHAR: NUMBER or DATE to character string TO_CHAR(2); TO_CHAR(SYSDATE, ‘MM/DD/YYYY HH:MI’); PL/SQL Data Type Conversion Functions

18  Concatenating strings: joining 2 or more character strings into a single string  Concatenation operator: || s_first_name := ‘Sarah’ s_last_name := ‘Miller’ s_full_name := s_first_name || ‘ ’ || s_last_name Character String Functions

19  RTRIM: removes blank trailing spaces cust_address := RTRIM(cust_address);  LENGTH: returns string length (number of characters) address_length := LENGTH(cust_address);  UPPER, LOWER: changes characters to all upper or lower case s_name := UPPER(s_name); s_name := LOWER(s_name); PL/SQL Character String Functions

20  INSTR: searches a string and looks for a matching substring and returns its starting position starting_position := INSTR(string_being_searched, search_string>); blank_position := INSTR(‘Sarah Miller’, ‘ ’); PL/SQL Character String Functions

21  SUBSTR: extracts a specific number of characters from a string, starting at a given point extracted_string := SUBSTR(string_being_searched, starting_point, number_of_characters_to_extract); s_first_name := SUBSTR(‘Sarah Miller’, 1,5); PL/SQL Character String Functions

22  Syntax error  Does not follow language guidelines  Causes a PLS- compile error  Examples: misspelling a reserved word, using a function incorrectly  Logic error  Program compiles correctly, but does not give correct output Debugging PL/SQL Programs

23  Isolate the line that is causing the error  This may be before or after the line that is flagged by the compiler  Comment out lines as necessary until program runs  One error may cause several cascading errors, so re-run program after fixing each error Locating and Correcting Syntax Errors

24 1.Identify the output variable(s) that have the error. 2.Identify the inputs and calculations that contribute to the error. 3.Display the values of the inputs using DBMS_OUTPUT commands. 4.Take a break and look at it again later. 5.Ask a fellow student for help. 6.Ask your instructor for help. Locating and Fixing Logic Errors

25 NULL Values in Assignment Statements Until a value is assigned to a variable, the variable’s value is NULL Performing an arithmetic value on a NULL value always results in a NULL value Advice: Always initialize variable values

26  IF/END IF: IF condition THEN program statements END IF;  IF/ELSE/END IF: IF condition THEN program statements ELSE alternate program statements END IF ;  IF/THEN PL/SQL Selection Structures

27  IF/ELSIF: IF condition1 THEN program statements; ELSIF condition2 THEN alternate program statements; ELSIF condition3 THEN alternate program statements;... ELSE alternate program statements; END IF; PL/SQL Selection Structures

28 PL/SQL Comparison Operators

29 Evaluating NULL Conditions in IF/THEN Structures If a condition evaluates as NULL, then it is FALSE How can a condition evaluate as NULL? It uses a BOOLEAN variable that has not been initialized It uses any other variable that has not been initialized

30 Using SQL Commands in PL/SQL Programs

31  Loop: repeats one or more program statements multiple times until an exit condition is reached  Pretest loop: exit condition is tested before program statements are executed  Posttest loop: exit condition is tested after program statements are executed PL/SQL Loops

32 LOOP program statements IF condition THEN EXIT; END IF; more program statements END LOOP;  LOOP … EXIT Pretest OR Posttest Pretest OR Posttest LOOP … EXIT Loop

33 LOOP program statements EXIT WHEN condition; END LOOP; Posttest LOOP … EXIT WHEN Loop

34  WHILE … LOOP WHILE condition LOOP program statements END LOOP; Pretest WHILE Loop

35 FOR counter_variable IN start_value.. end_value LOOP program statements END LOOP; Preset number of iterations Numeric FOR Loop

36 Cursors Pointer to a server memory location Contains information about a SQL command in a PL/SQL program Called the command’s context area

37 Cursor context area active set Number of rows processed Parsed command statement Database Server Memory Cursors

38  Implicit  Explicit Types of Cursors

39  Created automatically every time you use an INSERT, UPDATE, DELETE, or SELECT command  Doesn’t need to be declared  Can be used to assign the output of a SELECT command to one or more PL/SQL variables  Can only be used if query returns one and only one record Implicit Cursors

40 SELECT field1, field2, … INTO variable1, variable2, … FROM tablename WHERE search_condition_that_will_ return_a_single_record; Implicit Cursor Syntax

41  Must be declared in program DECLARE section  Can be used to assign the output of a SELECT command to one or more PL/SQL variables  Can be used if query returns multiple records or no records Explicit Cursors

42  Declare the cursor  Open the cursor  Fetch the cursor result into PL/SQL program variables  Close the cursor Using an Explicit Cursor

43 Declaring an Explicit Cursor DECLARE CURSOR cursor_name IS SELECT_statement;

44 Opening an Explicit Cursor OPEN cursor_name;

45 Fetching Explicit Cursor Records FETCH cursor_name INTO variable_name(s);

46 Closing an Explicit Cursor CLOSE cursor_name;

47 Processing an Explicit Cursor LOOP..EXIT WHEN approach: OPEN cursor_name; LOOP FETCH cursor_name INTO variable_name(s); EXIT WHEN cursor_name%NOTFOUND: END LOOP; CLOSE cursor_name;

48 Processing an Explicit Cursor Cursor FOR Loop approach: FOR variable_name(s) in cursor_name LOOP additional processing statements; END LOOP;

49 Using Reference Data Types in Explicit Cursor Processing  Declaring a ROWTYPE reference variable: DECLARE reference_variable_name cursor_name%ROWTYPE;  Referencing a ROWTYPE reference variable: reference_variable_name.database_field_name

50 Explicit Cursor Attributes

51  Data structure that contains multiple data items that are the same data type  Each table item has a key and a value  Key values do not need to be sequential  Used to create a lookup table that is stored in memory to improve processing speed PL/SQL Tables KeyValue 1Shadow 2Dusty 3Sassy

52 PL/SQL Table of Records PL/SQL table that can store multiple values that are referenced by a key Usually used to store database records that need to be processed by a PL/SQL program Improves performance by limiting number of database retrievals

53 PL/SQL Exception Handling All error handling statements are placed in the EXCEPTION program block Exception handler: program command that provides information about an error, and suggest correction actions

54  Common errors that have been given predefined names that appear instead of error numbers Predefined Exceptions

55 Exception Handler Syntax For Predefined Exceptions WHEN exception1_name THEN exception handling statements; WHEN exception2_name THEN exception handling statements; … WHEN OTHERS THEN exception handling statements;

56  Less-common errors that have not been given predefined names  ORA- error code appears  Exception handler tests for ORA- error code and provides alternate error message Undefined Exceptions

57  Errors that will not cause a run-time error, but will violate business rules  Programmer creates a custom error message User-Defined Exceptions

58 Nested PL/SQL Program Blocks An inner program block can be nested within an outer program block DECLARE variable declarations BEGIN program statements EXCEPTION error handling statements END; DECLARE variable declarations BEGIN program statements EXCEPTION error handling statements END; Inner block Outer block

59 Exception Handling in Nest Program Blocks If an exception is raised and handled in an inner block, program execution resumes in the outer block

60 DECLARE variable declarations BEGIN program statements additional program statements EXCEPTION error handling statements END; Exception Handling in Nested Program Blocks DECLARE exception_A BEGIN RAISE exception_A EXCEPTION exception_A error handler END; Exception is raised and handled in inner block Program execution resumes here

61 Exception Handling in Nested Program Blocks Exceptions raised in inner blocks can be handled by exception handlers in outer blocks