Oracle Database 10g: PL/SQL Fundamentals

Electronic Presentation

D17112GC30 Edition 3.0 April 2009

Authors
Salome Clement Sunitha Patel Tulika Srivastava

Copyright © 2009, Oracle. All rights reserved. Disclaimer This document contains proprietary information and is protected by copyright and other intellectual property laws. You may copy and print this document solely for your own use in an Oracle training course. The document may not be modified or altered in any way. Except where your use constitutes "fair use" under copyright law, you may not use, share, download, upload, copy, print, display, perform, reproduce, publish, license, post, transmit, or distribute this document in whole or in part without the express authorization of Oracle. The information contained in this document is subject to change without notice. If you find any problems in the document, please report them in writing to: Oracle University, 500 Oracle Parkway, Redwood Shores, California 94065 USA. This document is not warranted to be error-free. Restricted Rights Notice If this documentation is delivered to the United States Government or anyone using the documentation on behalf of the United States Government, the following notice is applicable: U.S. GOVERNMENT RIGHTS The U.S. Government’s rights to use, modify, reproduce, release, perform, display, or disclose these training materials are restricted by the terms of the applicable Oracle license agreement and/or the applicable U.S. Government contract. Trademark Notice Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.

Technical Contributors and Reviewers
Brian Boxx Christoph Burandt Zarko Cesljas Dairy Chan Isabelle Cornu Kathryn Cunningham Laszlo Czinkoczki Burt Demchick Laura Garza Joel Goodman Nancy Greenberg Joe Greenwald Jonathan Grove Punita Handa Jessie Ho Craig Hollister Alison Holloway Chaitanya Koratamaddi Bryn Llewellyn Malika Marghadi Hildegard Mayr Miyuki Osato Nagavalli Pataballa Srinivas Putrevu Bryan Roberts

Technical Contributors and Reviewers
Helen Robertson Grant Spencer Michael Versaci Lex Van Der Werff Yash Jain

Editors
Richard Wallis Arijit Ghosh

Graphic Designers
Steve Elwood Priya Saxena

Publishers
Sujatha Nagendra Michael Sebastian Nita Brozowski Srividya Rameshkumar

Introduction

Copyright © 2009, Oracle. All rights reserved.

Objectives
After completing this lesson, you should be able to do the following: • Describe the objectives of the course • Describe the course agenda • Identify the database tables used in the course • Identify the Oracle products that help you design a complete business solution

I-2

Copyright © 2009, Oracle. All rights reserved.

Course Objectives
After completing this course, you should be able to do the following: • Describe how PL/SQL provides programming extensions to SQL • Write PL/SQL code to interface with the database • Design PL/SQL program units that execute efficiently • Use PL/SQL programming constructs and conditional control statements • Handle run-time errors • Describe stored procedures and functions

I-3

Copyright © 2009, Oracle. All rights reserved.

. Oracle. Declaring PL/SQL Variables 3. All rights reserved.Course Agenda Lessons for the first day: I. Writing Executable Statements 4. Writing Control Structures I-4 Copyright © 2009. Interacting with the Oracle Server 5. Introduction 1. Introduction to PL/SQL 2.

Using Explicit Cursors 8. All rights reserved. Working with Composite Data Types 7.Course Agenda Lessons for the second day: 6. Handling Exceptions 9. . Creating Stored Procedures and Functions I-5 Copyright © 2009. Oracle.

Oracle. . All rights reserved.Human Resources (hr) Data Set I-6 Copyright © 2009.

Oracle. All rights reserved. .Oracle10g Grid Infrastructure I-8 Copyright © 2009.

. All rights reserved.Oracle Database 10g Object Relational Data Documents Multimedia Messages I-9 Copyright © 2009. Oracle.

All rights reserved. .Oracle Application Server 10g Portals Transactional applications Business intelligence Integration Application development framework I .10 Application server Copyright © 2009. Oracle.

Oracle.Oracle Enterprise Manager 10g Grid Control • • Software provisioning Application service-level monitoring I . .11 Copyright © 2009. All rights reserved.

Oracle. All rights reserved. .Oracle Internet Platform Clients Any browser Any Any mail client FTP client System management Internet applications Business logic Presentation and and data business logic Databases Application servers Development tools SQL PL/SQL Java Network services I .12 Copyright © 2009.

Oracle. you should have learned how to: • Describe the course objectives and course agenda • Identify tables and their relationships in the hr schema • Identify the various products in the Oracle 10g grid infrastructure that enable you to develop a complete business solution I .13 Copyright © 2009.Summary In this lesson. . All rights reserved.

Oracle. .Introduction to PL/SQL Copyright © 2009. All rights reserved.

you should be able to do the following: • Explain the need for PL/SQL • Explain the benefits of PL/SQL • Identify the different types of PL/SQL blocks • Use Oracle SQL Developer as a development environment for PL/SQL • Output messages from PL/SQL 1-2 Copyright © 2009. Oracle. . All rights reserved.Objectives After completing this lesson.

Oracle. . All rights reserved.What Is PL/SQL? PL/SQL: • Stands for Procedural Language extension to SQL • Is Oracle Corporation’s standard data access language for relational databases • Seamlessly integrates procedural constructs with SQL 1-3 Copyright © 2009.

Maintenance of code is made easier with such a welldefined structure. . Oracle. All rights reserved. and types – Control structures such as conditional statements and loops – Reusable program units that are written once and executed many times 1-4 Copyright © 2009. constants. • Provides procedural constructs such as: – Variables.About PL/SQL PL/SQL: • Provides a block structure for executable units of code.

Oracle.PL/SQL Environment PL/SQL engine procedural PL/SQL Block SQL Procedural Statement Executor SQL Statement Executor Oracle Database Server 1-5 Copyright © 2009. . All rights reserved.

.THEN SQL ELSE SQL END IF. All rights reserved.. Oracle. SQL 1-6 Copyright © 2009. .Benefits of PL/SQL • • Integration of procedural constructs with SQL Improved performance SQL 1 SQL 2 … SQL IF.

Oracle.Benefits of PL/SQL • • • • Modularized program development Integration with Oracle tools Portability Exception handling 1-7 Copyright © 2009. All rights reserved. .

(mandatory) 1-9 Copyright © 2009. Oracle. cursors. . user-defined exceptions BEGIN (mandatory) – SQL statements – PL/SQL statements • EXCEPTION (optional) – Actions to perform when errors occur • END.PL/SQL Block Structure • • DECLARE (optional) – Variables. All rights reserved.

[EXCEPTION] END. BEGIN --statements [EXCEPTION] END. 1 .11 Copyright © 2009. Oracle.Block Types Anonymous [DECLARE] Procedure PROCEDURE name IS BEGIN --statements [EXCEPTION] END. . Function FUNCTION name RETURN datatype IS BEGIN --statements RETURN value. All rights reserved.

.Program Constructs Tools Constructs Anonymous blocks Application procedures or functions Application packages Application triggers Object types 1 . All rights reserved.13 Database Server Constructs Anonymous blocks Stored procedures or functions Stored packages Database triggers Object types Copyright © 2009. Oracle.

All rights reserved. Oracle.PL/SQL Programming Environments Oracle JDeveloper 1 .15 Copyright © 2009. .

.PL/SQL Programming Environments Oracle SQL Developer 1 .16 Copyright © 2009. All rights reserved. Oracle.

Creating a Database Connection 1 . Oracle.17 Copyright © 2009. All rights reserved. .

.18 Copyright © 2009.Creating an Anonymous Block Enter the anonymous block in the SQL Developer workspace: 1 . Oracle. All rights reserved.

Oracle. All rights reserved. .Executing an Anonymous Block Click the Run Script button to execute the anonymous block: 1 .19 Copyright © 2009.

Testing the Output of a PL/SQL Block • Enable output in SQL Developer by clicking the Enable DBMS Output button on the DBMS Output tab: Enable DBMS Output DBMS Output Tab • Use a predefined Oracle package and its procedure: – DBMS_OUTPUT.PUT_LINE 1 . All rights reserved. .20 Copyright © 2009. Oracle.

.Testing the Output of a PL/SQL Block 1 . All rights reserved. Oracle.21 Copyright © 2009.

you should have learned how to: • Integrate SQL statements with PL/SQL program constructs • Identify the benefits of PL/SQL • Differentiate different PL/SQL block types • Use Oracle SQL Developer as the programming environment for PL/SQL • Output messages in PL/SQL 1 .Summary In this lesson.22 Copyright © 2009. Oracle. . All rights reserved.

All rights reserved. . Oracle.Practice 1: Overview This practice covers the following topics: • Identifying which PL/SQL blocks execute successfully • Creating and executing a simple PL/SQL block 1 .23 Copyright © 2009.

Declaring PL/SQL Variables Copyright © 2009. All rights reserved. Oracle. .

and print bind variables 2-2 Copyright © 2009. you should be able to do the following: • Identify valid and invalid identifiers • List the uses of variables • Declare and initialize variables • List and describe various data types • Identify the benefits of using the %TYPE attribute • Declare. All rights reserved. Oracle.Objectives After completing this lesson. . use.

department_id INTO emp_fname. . Oracle. emp_deptno FROM … Jennifer emp_fname 10 emp_deptno 2-3 Copyright © 2009. All rights reserved.Use of Variables Variables can be used for: • Temporary storage of data • Manipulation of stored values • Reusability SELECT first_name.

.Identifiers Identifiers are used for: • Naming a variable • Providing conventions for variable names – Must start with a letter – Can include letters or numbers – Can include special characters (such as dollar sign. All rights reserved. Oracle. and pound sign) – Must limit the length to 30 characters – Must not be reserved words 2-4 Copyright © 2009. underscore.

Handling Variables in PL/SQL Variables are: • Declared and initialized in the declarative section • Used and assigned new values in the executable section • Passed as parameters to PL/SQL subprograms • Used to hold the output of a PL/SQL subprogram 2-5 Copyright © 2009. All rights reserved. Oracle. .

Declaring and Initializing PL/SQL Variables Syntax identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr]. NUMBER(2) NOT NULL := 10. Examples DECLARE emp_hiredate emp_deptno location c_comm DATE. VARCHAR2(13) := 'Atlanta'. Oracle. CONSTANT NUMBER := 1400. All rights reserved. . 2-6 Copyright © 2009.

PUT_LINE('My name is: '||Myname). / 1 2 2-7 Copyright © 2009. DBMS_OUTPUT. BEGIN DBMS_OUTPUT. Myname := 'John'. END. / SET SERVEROUTPUT ON DECLARE Myname VARCHAR2(20):= 'John'. DBMS_OUTPUT. BEGIN Myname := 'Steven'.PUT_LINE('My name is: '||Myname). Oracle.Declaring and Initializing PL/SQL Variables SET SERVEROUTPUT ON DECLARE Myname VARCHAR2(20).PUT_LINE('My name is: '||Myname). END. All rights reserved. .

Delimiters in String Literals

SET SERVEROUTPUT ON DECLARE event VARCHAR2(15); BEGIN event := q'!Father's day!'; DBMS_OUTPUT.PUT_LINE('3rd Sunday in June is : '||event); event := q'[Mother's day]'; DBMS_OUTPUT.PUT_LINE('2nd Sunday in May is : '||event); END; /

2-8

Copyright © 2009, Oracle. All rights reserved.

Types of Variables
• PL/SQL variables:
– – – – Scalar Composite Reference Large object (LOB)

Non-PL/SQL variables: Bind variables

2-9

Copyright © 2009, Oracle. All rights reserved.

Types of Variables
TRUE 25-JAN-01 The soul of the lazy man desires, and he has nothing; but the soul of the diligent shall be made rich.

256120.08

Atlanta

2 - 10

Copyright © 2009, Oracle. All rights reserved.

Guidelines for Declaring and Initializing PL/SQL Variables
• • • • Follow naming conventions. Use meaningful names for variables. Initialize variables designated as NOT NULL and CONSTANT. Initialize variables with the assignment operator (:=) or the DEFAULT keyword:
Myname VARCHAR2(20):='John'; Myname VARCHAR2(20) DEFAULT 'John';

Declare one identifier per line for better readability and code maintenance.

2 - 11

Copyright © 2009, Oracle. All rights reserved.

Guidelines for Declaring and Initializing PL/SQL Variables
• Avoid using column names as identifiers.
DECLARE employee_id NUMBER(6); BEGIN SELECT employee_id INTO employee_id FROM employees WHERE last_name = 'Kochhar'; END; /

Use the NOT NULL constraint when the variable must hold a value.

2 - 12

Copyright © 2009, Oracle. All rights reserved.

. but the soul of the diligent shall be made rich.13 Copyright © 2009. All rights reserved. and he has nothing. Oracle.Scalar Data Types • • Hold a single value Have no internal components TRUE 25-JAN-01 The soul of the lazy man desires. 256120.08 Atlanta 2 .

Oracle. scale)] BINARY_INTEGER PLS_INTEGER BOOLEAN BINARY_FLOAT BINARY_DOUBLE 2 . All rights reserved.Base Scalar Data Types • • • • • • • • • • CHAR [(maximum_length)] VARCHAR2 (maximum_length) LONG LONG RAW NUMBER [(precision. .14 Copyright © 2009.

. All rights reserved.16 Copyright © 2009.Base Scalar Data Types • • • • • • DATE TIMESTAMP TIMESTAMP WITH TIME ZONE TIMESTAMP WITH LOCAL TIME ZONE INTERVAL YEAR TO MONTH INTERVAL DAY TO SECOND 2 . Oracle.

BINARY_FLOAT and BINARY_DOUBLE • • • • Represent floating point numbers in IEEE 754 format Offer better interoperability and operational speed Store values beyond the values that the data type NUMBER can store Provide the benefits of closed arithmetic operations and transparent rounding 2 .18 Copyright © 2009. All rights reserved. . Oracle.

20 Copyright © 2009. All rights reserved.. Oracle. VARCHAR2(9). CONSTANT NUMBER(3. BINARY_INTEGER := 0. DATE := SYSDATE + 7. NUMBER(9.Declaring Scalar Variables Examples DECLARE emp_job count_loop dept_total_sal orderdate c_tax_rate valid .2) := 8.25.. BOOLEAN NOT NULL := TRUE.2) := 0. 2 . .

. Oracle.21 Copyright © 2009.%TYPE Attribute The %TYPE attribute • Is used to declare a variable according to: – A database column definition – Another declared variable • Is prefixed with: – The database table and column – The name of the declared variable 2 . All rights reserved.

. emp_lname balance min_balance .23 Copyright © 2009. balance%TYPE := 1000. Oracle.column_name%TYPE..last_name%TYPE. NUMBER(7.. 2 ..Declaring Variables with the %TYPE Attribute Syntax identifier table.2).. employees. All rights reserved. Examples .

• • 2 . and NULL can be assigned to a Boolean variable. Arithmetic. FALSE. Oracle. character. and date expressions can be used to return a Boolean value. The variables always yield TRUE. Conditional expressions use the logical operators AND and OR and the unary operator NOT to check the variable values.Declaring Boolean Variables • • Only the values TRUE. All rights reserved. FALSE. . or NULL.24 Copyright © 2009.

.25 Copyright © 2009. Oracle. All rights reserved.Bind Variables Bind variables are: • Created in the environment • Also called host variables • Created with the VARIABLE keyword • • • Used in SQL statements and PL/SQL blocks Accessed even after the PL/SQL block is executed Referenced with a preceding colon 2 .

Printing Bind Variables Example VARIABLE emp_salary NUMBER BEGIN SELECT salary INTO :emp_salary FROM employees WHERE employee_id = 178. .27 Copyright © 2009. Oracle. / PRINT emp_salary SELECT first_name. END. last_name FROM employees WHERE salary=:emp_salary. 2 . All rights reserved.

/ 2 . END. .28 Copyright © 2009.Printing Bind Variables Example VARIABLE emp_salary NUMBER SET AUTOPRINT ON BEGIN SELECT salary INTO :emp_salary FROM employees WHERE employee_id = 178. Oracle. All rights reserved.

. END.29 Copyright © 2009. All rights reserved. / 2 .Substitution Variables • • • Are used to get user input at run time Are referenced within a PL/SQL block with a preceding ampersand Are used to avoid hard-coding values that can be obtained at run time VARIABLE emp_salary NUMBER SET AUTOPRINT ON DECLARE empno NUMBER(6):=&empno. BEGIN SELECT salary INTO :emp_salary FROM employees WHERE employee_id = empno. Oracle.

30 Copyright © 2009. Oracle. .Substitution Variables 1 2 2 . All rights reserved.

31 Copyright © 2009. BEGIN SELECT salary INTO :emp_salary FROM employees WHERE employee_id = empno. / 2 . All rights reserved.Prompt for Substitution Variables SET VERIFY OFF VARIABLE emp_salary NUMBER ACCEPT empno PROMPT 'Please enter a valid employee number: ' SET AUTOPRINT ON DECLARE empno NUMBER(6):= &empno. . Oracle. END.

. Oracle. BEGIN SELECT first_name INTO fname FROM employees WHERE last_name='&lname'.Using DEFINE for a User Variable Example SET VERIFY OFF DEFINE lname= Urman DECLARE fname VARCHAR2(25). END.32 Copyright © 2009. / 2 . All rights reserved.

33 Copyright © 2009. All rights reserved.Composite Data Types TRUE 23-DEC-98 ATLANTA PL/SQL table structure PL/SQL table structure 1 2 3 4 SMITH JONES NANCY TIM VARCHAR2 PLS_INTEGER 1 2 3 4 5000 2345 12 3456 NUMBER PLS_INTEGER 2 . . Oracle.

Oracle.34 Copyright © 2009.LOB Data Type Variables Book (CLOB) Photo (BLOB) Movie (BFILE) NCLOB 2 . All rights reserved. .

35 Copyright © 2009. Oracle. you should have learned how to: • Recognize valid and invalid identifiers • Declare variables in the declarative section of a PL/SQL block • Initialize variables and use them in the executable section • Differentiate between scalar and composite data types • Use the %TYPE attribute • Use bind variables 2 . . All rights reserved.Summary In this lesson.

Practice 2: Overview This practice covers the following topics: • Determining valid identifiers • Determining valid variable declarations • Declaring variables within an anonymous block • Using the %TYPE attribute to declare variables • • Declaring and printing a bind variable Executing a PL/SQL block 2 . . Oracle. All rights reserved.36 Copyright © 2009.

Writing Executable Statements Copyright © 2009. All rights reserved. Oracle. .

. you should be able to do the following: • Identify lexical units in a PL/SQL block • Use built-in SQL functions in PL/SQL • Describe when implicit conversions take place and when explicit conversions have to be dealt with • Write nested blocks and qualify variables with labels • Write readable code with appropriate indentations 3-2 Copyright © 2009.Objectives After completing this lesson. Oracle. All rights reserved.

. returns. Oracle. tabs.Lexical Units in a PL/SQL Block Lexical units: • Are building blocks of any PL/SQL block • Are sequences of characters including letters. All rights reserved. spaces. numerals. and symbols • Can be classified as: – – – – Identifiers Delimiters Literals Comments 3-3 Copyright © 2009.

All rights reserved. Oracle. – Numbers can be simple values or scientific notation. . • Statements can continue over several lines. 3-5 Copyright © 2009. name := 'Henderson'.PL/SQL Block Syntax and Guidelines • Literals: – Character and date literals must be enclosed in single quotation marks.

Place multiple-line comments between the symbols /* and */. Oracle.This is the end of the block / • • 3-6 Copyright © 2009.Begin the executable section /* Compute the annual salary based on the monthly salary input from the user */ annual_sal := monthly_sal * 12. -. Example DECLARE . END.2).Commenting Code Prefix single-line comments with two hyphens (--). . annual_sal NUMBER (9... BEGIN -. All rights reserved.

. Oracle.SQL Functions in PL/SQL • Available in procedural statements: – – – – – – Single-row number Single-row character Data type conversion Date Timestamp GREATEST and LEAST – Miscellaneous functions • Not available in procedural statements: – DECODE – Group functions 3-7 Copyright © 2009. All rights reserved.

. All rights reserved. prod_description VARCHAR2(70):='You can use this product with your radios for higher frequency'. 3-8 Copyright © 2009. Oracle. -. • Convert the employee name to lowercase: emp_name:= LOWER(emp_name).get the length of the string in prod_description desc_size:= LENGTH(prod_description).SQL Functions in PL/SQL: Examples • Get the length of a string: desc_size INTEGER(5).

Data Type Conversions • • Convert data to comparable data types Are of two types: – Implicit conversions – Explicit conversions • Some conversion functions: – – – – TO_CHAR TO_DATE TO_NUMBER TO_TIMESTAMP 3-9 Copyright © 2009. . All rights reserved. Oracle.

date_of_joining DATE:= 'February 02. YYYY').'Month DD. Oracle.11 Copyright © 2009. All rights reserved. . 3 .2000'.Data Type Conversion 1 2 date_of_joining DATE:= '02-Feb-2000'. 3 date_of_joining DATE:= TO_DATE('February 02.2000'.

All rights reserved. • An exception section can contain nested blocks. 3 . • An executable section (BEGIN … END) can contain nested blocks. . Oracle.Nested Blocks PL/SQL blocks can be nested.12 Copyright © 2009.

BEGIN DBMS_OUTPUT. All rights reserved.Nested Blocks Example: DECLARE outer_variable VARCHAR2(20):='GLOBAL VARIABLE'.PUT_LINE(outer_variable). BEGIN DECLARE inner_variable VARCHAR2(20):='LOCAL VARIABLE'.PUT_LINE(inner_variable). DBMS_OUTPUT. END.13 Copyright © 2009. END.PUT_LINE(outer_variable). DBMS_OUTPUT. / 3 . Oracle. .

DBMS_OUTPUT. BEGIN DBMS_OUTPUT. date_of_birth DATE:='20-Apr-1972'. END. . DBMS_OUTPUT.PUT_LINE('Date of Birth: '||date_of_birth).PUT_LINE('Father''s Name: '||father_name).Variable Scope and Visibility 1 2 DECLARE father_name VARCHAR2(20):='Patrick'. DBMS_OUTPUT.14 Copyright © 2009. Oracle. date_of_birth DATE:='12-Dec-2002'. All rights reserved.PUT_LINE('Date of Birth: '||date_of_birth). / 3 . END.PUT_LINE('Child''s Name: '||child_name). BEGIN DECLARE child_name VARCHAR2(20):='Mike'.

BEGIN DECLARE child_name VARCHAR2(20):='Mike'. .PUT_LINE('Father''s Name: '||father_name). All rights reserved. END.16 Copyright © 2009. DBMS_OUTPUT. DBMS_OUTPUT.PUT_LINE('Date of Birth: ' ||outer. date_of_birth DATE:='20-Apr-1972'.PUT_LINE('Date of Birth: '||date_of_birth).Qualify an Identifier BEGIN <<outer>> DECLARE father_name VARCHAR2(20):='Patrick'.date_of_birth).PUT_LINE('Child''s Name: '||child_name). END outer. END. date_of_birth DATE:='12-Dec-2002'. BEGIN DBMS_OUTPUT. 3 . Oracle. DBMS_OUTPUT.

message VARCHAR2(255) := ' eligible for commission'.30.comm := sal * 0. END outer.2) := sal * 0. total_comp NUMBER(7. . END.17 Copyright © 2009. All rights reserved. comm NUMBER(7.2) := 50000. / 1 2 3 .2) := 60000. Oracle. BEGIN message := 'CLERK not'||message.20. message := 'SALESMAN'||message.Determining Variable Scope BEGIN <<outer>> DECLARE sal NUMBER(7. BEGIN DECLARE sal NUMBER(7. comm NUMBER(7.2) := 0.2) := sal + comm. outer. END.

Operators in PL/SQL • • • • Logical Arithmetic Concatenation Parentheses to control order of operations Exponential operator (**) Same as in SQL • 3 . Oracle. .18 Copyright © 2009. All rights reserved.

19 Copyright © 2009.Operators in PL/SQL Examples: • Increment the counter for a loop. . • Set the value of a Boolean flag. loop_count := loop_count + 1. • Validate whether an employee number contains a value. Oracle. 3 . All rights reserved. good_sal := sal BETWEEN 50000 AND 150000. valid := (empno IS NOT NULL).

All rights reserved.Programming Guidelines Make code maintenance easier by: • Documenting code with comments • Developing a case convention for the code • Developing naming conventions for identifiers and other objects • Enhancing readability by indenting 3 . Oracle. .20 Copyright © 2009.

END IF. indent each level of code. .21 Copyright © 2009. All rights reserved. ... location_id INTO deptno. BEGIN SELECT department_id. / deptno NUMBER(4). END. END. location_id FROM departments WHERE department_name = 'Sales'.Indenting Code For clarity. location_id NUMBER(4). / 3 . Oracle. DECLARE Example: BEGIN IF x=0 THEN y:=1.

22 Copyright © 2009. you should have learned how to: • Use built-in SQL functions in PL/SQL • Write nested blocks to break logically related functionalities • Decide when to perform explicit conversions • Qualify variables in nested blocks 3 . . All rights reserved. Oracle.Summary In this lesson.

All rights reserved.23 Copyright © 2009.Practice 3: Overview This practice covers the following topics: • Reviewing scoping and nesting rules • Writing and testing PL/SQL blocks 3 . Oracle. .

Oracle.Interacting with the Oracle Server Copyright © 2009. . All rights reserved.

Objectives After completing this lesson. Oracle. . you should be able to do the following: • Determine which SQL statements can be directly included in a PL/SQL executable block • Manipulate data with DML statements in PL/SQL • Use transaction control statements in PL/SQL • Use the INTO clause to hold the values returned by a SQL statement • Differentiate between implicit cursors and explicit cursors • Use SQL cursor attributes 4-2 Copyright © 2009. All rights reserved.

SQL Statements in PL/SQL • • • Retrieve a row from the database by using the SELECT command. Make changes to rows in the database by using DML commands. All rights reserved. ROLLBACK. Control a transaction with the COMMIT. . Oracle. or SAVEPOINT command. 4-3 Copyright © 2009.

Oracle. variable_name]. Syntax: SELECT INTO FROM [WHERE select_list {variable_name[... | record_name} table condition]. All rights reserved.SELECT Statements in PL/SQL Retrieve data from the database with a SELECT statement. 4-5 Copyright © 2009. .

. Example SET SERVEROUTPUT ON DECLARE fname VARCHAR2(25). All rights reserved.PUT_LINE(' First Name is : '||fname). Oracle. Queries must return only one row.SELECT Statements in PL/SQL • • The INTO clause is required. BEGIN SELECT first_name INTO fname FROM employees WHERE employee_id=200. END. / 4-7 Copyright © 2009. DBMS_OUTPUT.

salary INTO emp_hiredate.hire_date%TYPE. emp_salary employees. BEGIN SELECT hire_date. Oracle.Retrieving Data in PL/SQL Retrieve hire_date and salary for the specified employee. / 4-9 Copyright © 2009. END. . emp_salary FROM employees WHERE employee_id = 100. Example: DECLARE emp_hiredate employees.salary%TYPE. All rights reserved.

group function INTO sum_sal FROM employees WHERE department_id = deptno. END. . BEGIN SELECT SUM(salary) -. deptno NUMBER NOT NULL := 60. DBMS_OUTPUT.2). Oracle.10 Copyright © 2009.Retrieving Data in PL/SQL Return the sum of the salaries for all the employees in the specified department. Example: SET SERVEROUTPUT ON DECLARE sum_sal NUMBER(10.PUT_LINE ('The sum of salary is ' || sum_sal). / 4 . All rights reserved.

employee_id employees. END. . sysdate FROM employees WHERE employee_id = employee_id. BEGIN SELECT hire_date.employee_id%TYPE := 176.hire_date%TYPE. Oracle. All rights reserved.11 Copyright © 2009. sysdate hire_date%TYPE.Naming Conventions DECLARE hire_date employees. / 4 . sysdate INTO hire_date.

The names of database table columns take precedence over the names of local variables.12 Copyright © 2009. All rights reserved. . Oracle. 4 . Avoid using database column names as identifiers.Naming Conventions • • • • • Use a naming convention to avoid ambiguity in the WHERE clause. The names of local variables and formal parameters take precedence over the names of database tables. Syntax errors can arise because PL/SQL checks the database first for a column in the table.

. All rights reserved.13 Copyright © 2009.Manipulating Data Using PL/SQL Make changes to database tables by using DML commands: • INSERT • UPDATE DELETE • DELETE • MERGE INSERT UPDATE MERGE 4 . Oracle.

sysdate. 'Cores'. job_id. email. 'Ruth'.Inserting Data Add new employee information to the EMPLOYEES table. All rights reserved. 'AD_ASST'.14 Copyright © 2009. / 4 . 'RCORES'. Oracle. last_name. first_name. salary) VALUES(employees_seq. 4000).NEXTVAL. END. Example: BEGIN INSERT INTO employees (employee_id. . hire_date.

salary%TYPE := 800. Example: DECLARE sal_increase employees. / 4 . Oracle. .Updating Data Increase the salary of all employees who are stock clerks. All rights reserved. BEGIN UPDATE employees SET salary = salary + sal_increase WHERE job_id = 'ST_CLERK'.15 Copyright © 2009. END.

16 Copyright © 2009. Example: DECLARE deptno employees. Oracle. / 4 . All rights reserved. .department_id%TYPE := 10. BEGIN DELETE FROM employees WHERE department_id = deptno. END.Deleting Data Delete rows that belong to department 10 from the employees table.

WHEN NOT MATCHED THEN INSERT VALUES(e.department_id). c. . e.last_name.employee_id = c. e..email. All rights reserved.e.employee_id%TYPE := 100.17 Copyright © 2009. .first_name. / 4 .first_name. Oracle.email = e. . END. .Merging Rows Insert or update rows in the copy_emp table to match the employees table.employee_id.empno) WHEN MATCHED THEN UPDATE SET c.first_name = e. BEGIN MERGE INTO copy_emp c USING employees e ON (e. .last_name.last_name = e. . c. DECLARE empno employees. .

19 Copyright © 2009.SQL Cursor • • A cursor is a pointer to the private memory area allocated by the Oracle server. Oracle. . There are two types of cursors: – Implicit: Created and managed internally by the Oracle server to process SQL statements – Explicit: Explicitly declared by the programmer 4 . All rights reserved.

SQL Cursor Attributes for Implicit Cursors Using SQL cursor attributes. SQL%FOUND Boolean attribute that evaluates to TRUE if the most recent SQL statement returned at least one row SQL%NOTFOUND Boolean attribute that evaluates to TRUE if the most recent SQL statement did not return even one row SQL%ROWCOUNT An integer value that represents the number of rows affected by the most recent SQL statement 4 . Oracle. you can test the outcome of your SQL statements. All rights reserved. .21 Copyright © 2009.

/ PRINT rows_deleted 4 . .22 Copyright © 2009. BEGIN DELETE FROM employees WHERE employee_id = empno. :rows_deleted := (SQL%ROWCOUNT || ' row deleted.SQL Cursor Attributes for Implicit Cursors Delete rows that have the specified employee ID from the employees table. Example VARIABLE rows_deleted VARCHAR2(30) DECLARE empno employees. Oracle. Print the number of rows deleted. All rights reserved.'). END.employee_id%TYPE := 176.

which is mandatory for all SELECT statements in PL/SQL • Differentiate between implicit cursors and explicit cursors • Use SQL cursor attributes to determine the outcome of SQL statements 4 . All rights reserved. Oracle. transaction control statements. .23 Copyright © 2009. you should have learned how to: • Embed DML statements.Summary In this lesson. and DDL statements in PL/SQL • Use the INTO clause.

Practice 4: Overview This practice covers the following topics: • Selecting data from a table • Inserting data into a table • Updating data in a table • Deleting a record from a table 4 . .24 Copyright © 2009. All rights reserved. Oracle.

Writing Control Structures Copyright © 2009. Oracle. . All rights reserved.

All rights reserved. . you should be able to do the following: • Identify the uses and types of control structures • Construct an IF statement • Use CASE statements and CASE expressions • • Construct and identify different loop statements Use guidelines when using conditional control structures 5-2 Copyright © 2009.Objectives After completing this lesson. Oracle.

All rights reserved. Oracle. .Controlling Flow of Execution for loop while 5-3 Copyright © 2009.

.] [ELSE statements. Oracle.] END IF.IF Statements Syntax: IF condition THEN statements. All rights reserved. [ELSIF condition THEN statements. 5-4 Copyright © 2009.

PUT_LINE(' I am a child '). Oracle. BEGIN IF myage < 11 THEN DBMS_OUTPUT. All rights reserved. END IF. . / 5-6 Copyright © 2009.Simple IF Statement DECLARE myage number:=31. END.

. END IF. Oracle. All rights reserved.IF THEN ELSE Statement SET SERVEROUTPUT ON DECLARE myage number:=31. END. ELSE DBMS_OUTPUT. / 5-7 Copyright © 2009.PUT_LINE(' I am a child ').PUT_LINE(' I am not a child '). BEGIN IF myage < 11 THEN DBMS_OUTPUT.

am in my thirties'). am in my twenties'). 5-8 Copyright © 2009.PUT_LINE(' I ELSIF myage < 40 THEN DBMS_OUTPUT. always young '). .PUT_LINE(' I ELSIF myage < 30 THEN DBMS_OUTPUT. All rights reserved. Oracle. BEGIN IF myage < 11 THEN DBMS_OUTPUT.IF ELSIF ELSE Clause DECLARE myage number:=31.PUT_LINE(' I ELSIF myage < 20 THEN DBMS_OUTPUT.PUT_LINE(' I am END IF. / am a child ').PUT_LINE(' I ELSE DBMS_OUTPUT. END. am young ').

. / 5-9 Copyright © 2009. ELSE DBMS_OUTPUT. Oracle. BEGIN IF myage < 11 THEN DBMS_OUTPUT. END IF.PUT_LINE(' I am not a child '). All rights reserved.PUT_LINE(' I am a child '). END.NULL Values in IF Statements DECLARE myage number.

. Oracle. WHEN expressionN THEN resultN [ELSE resultN+1] END. The value returned by these expressions is used to select one of several alternatives. To select the result.CASE Expressions • • A CASE expression selects a result and returns it. CASE selector WHEN expression1 THEN result1 WHEN expression2 THEN result2 . / 5 . the CASE expression uses expressions..10 Copyright © 2009. All rights reserved. .

All rights reserved. / 5 . Oracle. BEGIN appraisal := CASE grade WHEN 'A' THEN 'Excellent' WHEN 'B' THEN 'Very Good' WHEN 'C' THEN 'Good' ELSE 'No such grade' END. DBMS_OUTPUT. END.PUT_LINE ('Grade: '|| grade || ' Appraisal ' || appraisal). .CASE Expressions: Example SET SERVEROUTPUT ON SET VERIFY OFF DECLARE grade CHAR(1) := UPPER('&grade').11 Copyright © 2009. appraisal VARCHAR2(20).

'C') THEN 'Good' ELSE 'No such grade' END. .PUT_LINE ('Grade: '|| grade || ' Appraisal ' || appraisal). appraisal VARCHAR2(20). / 5 . All rights reserved.Searched CASE Expressions DECLARE grade CHAR(1) := UPPER('&grade'). BEGIN appraisal := CASE WHEN grade = 'A' THEN 'Excellent' WHEN grade IN ('B'. END. DBMS_OUTPUT.12 Copyright © 2009. Oracle.

deptname FROM departments WHERE manager_id=108. Oracle. WHEN 200 THEN . deptname VARCHAR2(20). / 5 . All rights reserved.CASE Statement DECLARE deptid NUMBER. END. department_name INTO deptid. SELECT count(*) INTO emps FROM employees WHERE department_id=deptid... BEGIN CASE mngid WHEN 108 THEN SELECT department_id.13 Copyright © 2009. DBMS_OUTPUT. . mngid NUMBER:= 108.PUT_LINE ('You are working in the '|| deptname|| ' department. emps NUMBER. END CASE. There are '||emps ||' employees in this department').

All rights reserved.14 Copyright © 2009. Oracle. 5 . . • Applying the logical operator NOT to a null yields NULL.Handling Nulls When working with nulls. • If the condition yields NULL in conditional control statements. its associated sequence of statements is not executed. you can avoid some common mistakes by keeping in mind the following rules: • Simple comparisons involving nulls always yield NULL.

AND TRUE FALSE NULL OR TRUE FALSE NULL NOT TRUE TRUE FALSE NULL TRUE TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE NULL FALSE TRUE NULL NULL FALSE NULL NULL TRUE NULL NULL NULL NULL 5 . . All rights reserved.15 Copyright © 2009. Oracle.Logic Tables Build a simple Boolean condition with a comparison operator.

16 Copyright © 2009. . Oracle. REORDER_FLAG TRUE TRUE NULL NULL AVAILABLE_FLAG TRUE FALSE TRUE FALSE FLAG ? (1) ? (2) ? (3) ? (4) 5 . All rights reserved.Boolean Conditions What is the value of flag in each case? flag := reorder_flag AND available_flag.

17 Copyright © 2009. There are three loop types: – Basic loop – FOR loop – WHILE loop 5 . .Iterative Control: LOOP Statements • • Loops repeat a statement or sequence of statements multiple times. All rights reserved. Oracle.

. . EXIT [WHEN condition]. All rights reserved. . END LOOP. 5 . Oracle.18 Copyright © 2009. .Basic Loops Syntax: LOOP statement1.

city. loc_id locations.city%TYPE := 'Montreal'.location_id%TYPE. Oracle. All rights reserved. END LOOP. counter := counter + 1. END. / 5 . BEGIN SELECT MAX(location_id) INTO loc_id FROM locations WHERE country_id = countryid. LOOP INSERT INTO locations(location_id. counter NUMBER(2) := 1. countryid). country_id) VALUES((loc_id + counter).19 Copyright © 2009.country_id%TYPE := 'CA'. EXIT WHEN counter > 3.Basic Loops Example DECLARE countryid locations. new_city. new_city locations. .

. .WHILE Loops Syntax: WHILE condition LOOP statement1. . END LOOP. statement2. Use the WHILE loop to repeat statements while a condition is TRUE.20 Copyright © 2009. 5 . Oracle. All rights reserved. .

/ 5 .country_id%TYPE := 'CA'.21 Copyright © 2009. Oracle.city%TYPE := 'Montreal'. counter NUMBER := 1. WHILE counter <= 3 LOOP INSERT INTO locations(location_id. countryid). END. new_city locations. city.WHILE Loops Example DECLARE countryid locations. END LOOP. BEGIN SELECT MAX(location_id) INTO loc_id FROM locations WHERE country_id = countryid.location_id%TYPE. All rights reserved. loc_id locations. country_id) VALUES((loc_id + counter). counter := counter + 1. . new_city.

All rights reserved. it is declared implicitly.. 'lower_bound .upper_bound LOOP statement1. END LOOP. 5 . . Oracle. statement2. . .FOR Loops • • • Use a FOR loop to shortcut the test for the number of iterations. Do not declare the counter.22 Copyright © 2009. . FOR counter IN [REVERSE] lower_bound. upper_bound' is required syntax..

Oracle. city. countryid ). BEGIN SELECT MAX(location_id) INTO loc_id FROM locations WHERE country_id = countryid.country_id%TYPE := 'CA'. new_city.. FOR i IN 1.24 Copyright © 2009. new_city locations.FOR Loops Example: DECLARE countryid locations. country_id) VALUES((loc_id + i). / 5 . loc_id locations. END LOOP. .3 LOOP INSERT INTO locations(location_id.city%TYPE := 'Montreal'.location_id%TYPE. All rights reserved. END.

it is undefined outside the loop.FOR Loops Guidelines • Reference the counter within the loop only.25 Copyright © 2009. • Neither loop bound should be NULL. All rights reserved. Oracle. • Do not reference the counter as the target of an assignment. 5 . .

Guidelines for Loops • • • Use the basic loop when the statements inside the loop must execute at least once. All rights reserved. Use a FOR loop if the number of iterations is known. . Oracle.26 Copyright © 2009. Use the WHILE loop if the condition must be evaluated at the start of each iteration. 5 .

5 . .27 Copyright © 2009. Use labels to distinguish between blocks and loops. Exit the outer loop with the EXIT statement that references the label. Oracle. All rights reserved.Nested Loops and Labels • • • You can nest loops to multiple levels.

Nested Loops and Labels
... BEGIN <<Outer_loop>> LOOP counter := counter+1; EXIT WHEN counter>10; <<Inner_loop>> LOOP ... EXIT Outer_loop WHEN total_done = 'YES'; -- Leave both loops EXIT WHEN inner_done = 'YES'; -- Leave inner loop only ... END LOOP Inner_loop; ... END LOOP Outer_loop; END; /

5 - 28

Copyright © 2009, Oracle. All rights reserved.

Summary
In this lesson, you should have learned how to change the logical flow of statements by using the following control structures: • Conditional (IF statement) • CASE expressions and CASE statements • Loops:
– Basic loop – FOR loop – WHILE loop

EXIT statements

5 - 29

Copyright © 2009, Oracle. All rights reserved.

Practice 5: Overview
This practice covers the following topics: • Performing conditional actions by using the IF statement • Performing iterative steps by using the loop structure

5 - 30

Copyright © 2009, Oracle. All rights reserved.

Working with Composite Data Types

Copyright © 2009, Oracle. All rights reserved.

Objectives
After completing this lesson, you should be able to do the following: • Create user-defined PL/SQL records • Create a record with the %ROWTYPE attribute • Create an INDEX BY table • Create an INDEX BY table of records • Describe the differences among records, tables, and tables of records

6-2

Copyright © 2009, Oracle. All rights reserved.

All rights reserved. . Oracle.Composite Data Types • • Can hold multiple values (unlike scalar types) Are of two types: – PL/SQL records – PL/SQL collections — — — INDEX BY tables or associative arrays Nested table VARRAY 6-3 Copyright © 2009.

Oracle. 6-4 Copyright © 2009. All rights reserved.Composite Data Types • • Use PL/SQL records when you want to store values of different data types but only one occurrence at a time. Use PL/SQL collections when you want to store values of the same data type. .

Oracle. . RECORD.PL/SQL Records • • • • • Must contain one or more components (called fields) of any scalar. All rights reserved. or INDEX BY table data type Are similar to structures in most 3GL languages (including C and C++) Are user defined and can be a subset of a row in a table Treat a collection of fields as a logical unit Are convenient for fetching a row of data from a table for processing 6-5 Copyright © 2009.

field_declaration]…).column%TYPE | table%ROWTYPE} [[NOT NULL] {:= | DEFAULT} expr] 6-6 Copyright © 2009.Creating a PL/SQL Record Syntax: 1 TYPE type_name IS RECORD (field_declaration[. 2 identifier type_name. field_declaration: field_name {field_type | variable%TYPE | table. . All rights reserved. Oracle.

Creating a PL/SQL Record Declare variables to store the name. and salary of a new employee. job.. Example: . . salary NUMBER(8. Oracle..2)). TYPE emp_record_type IS RECORD (last_name VARCHAR2(25)... 6-7 Copyright © 2009. . emp_record emp_record_type. job_id VARCHAR2(10). All rights reserved.

Oracle. .PL/SQL Record Structure Field1 (data type) Field2 (data type) Field3 (data type) Example: Field1 (data type) Field2 (data type) Field3 (data type) employee_id number(6) last_name varchar2(25) job_id varchar2(10) 100 King AD_PRES 6-8 Copyright © 2009. All rights reserved.

. 6-9 Copyright © 2009. Fields in the record take their names and data types from the columns of the table or view.%ROWTYPE Attribute • • • Declare a variable according to a collection of columns in a database table or view. Syntax: DECLARE identifier reference%ROWTYPE. All rights reserved. Oracle. Prefix %ROWTYPE with the database table or view.

• 6 .Advantages of Using %ROWTYPE • The number and data types of the underlying database columns need not be known—and in fact might change at run time.11 Copyright © 2009. The %ROWTYPE attribute is useful when retrieving a row with the SELECT * statement. . All rights reserved. Oracle.

SYSDATE. emp_rec.12 Copyright © 2009. emp_rec. leavedate. emp_rec. / employees%ROWTYPE.hire_date. DEFINE employee_number = 124 DECLARE emp_rec BEGIN SELECT * INTO emp_rec FROM employees WHERE employee_id = &employee_number. END.salary. mgr.commission_pct.manager_id. ename. 6 .emp_rec. deptno) VALUES (emp_rec.job_id.department_id). . comm. emp_rec.%ROWTYPE Attribute . sal. INSERT INTO retired_emps(empno.employee_id.last_name. Oracle. All rights reserved. hiredate. emp_rec. emp_rec. job...

. employee_id = &employee_number. job_id. 6 . / SELECT * FROM retired_emps. manager_id.Inserting a Record by Using %ROWTYPE . INSERT INTO retired_emps VALUES emp_rec. All rights reserved.. last_name. hire_date. Oracle. retired_emps%ROWTYPE. DEFINE employee_number = 124 DECLARE emp_rec BEGIN SELECT employee_id.13 Copyright © 2009.. hire_date. salary. commission_pct. department_id INTO emp_rec FROM employees WHERE END.

BEGIN SELECT * INTO emp_rec FROM retired_emps. UPDATE retired_emps SET ROW = emp_rec WHERE empno=&employee_number. All rights reserved. 6 . emp_rec. END. Oracle.14 Copyright © 2009.Updating a Row in a Table by Using a Record SET SERVEROUTPUT ON SET VERIFY OFF DEFINE employee_number = 124 DECLARE emp_rec retired_emps%ROWTYPE. .leavedate:=SYSDATE. / SELECT * FROM retired_emps.

All rights reserved. the size depends on the values that the key data type can hold.15 Copyright © 2009.INDEX BY Tables or Associative Arrays • Are PL/SQL structures with two columns: – Primary key of integer or string data type – Column of scalar or record data type • Are unconstrained in size. Oracle. However. 6 . .

Creating an INDEX BY Table Syntax: TYPE type_name IS TABLE OF {column_type | variable%TYPE | table. identifier type_name..last_name%TYPE INDEX BY PLS_INTEGER. 6 .column%TYPE} [NOT NULL] | table%ROWTYPE [INDEX BY PLS_INTEGER | BINARY_INTEGER | VARCHAR2(<size>)].. .16 Copyright © 2009.. All rights reserved.. TYPE ename_table_type IS TABLE OF employees. . Oracle. ename_table ename_table_type. Declare an INDEX BY table to store the last names of employees: .

. PLS_INTEGER Value . .18 Copyright © 2009. Scalar 6 . 1 5 3 .. Jones Smith Maduro ... All rights reserved...INDEX BY Table Structure Unique key .. Oracle..

Creating an INDEX BY Table
DECLARE TYPE ename_table_type IS TABLE OF employees.last_name%TYPE INDEX BY PLS_INTEGER; TYPE hiredate_table_type IS TABLE OF DATE INDEX BY PLS_INTEGER; ename_table ename_table_type; hiredate_table hiredate_table_type; BEGIN ename_table(1) := 'CAMERON'; hiredate_table(8) := SYSDATE + 7; IF ename_table.EXISTS(1) THEN INSERT INTO ... ... END;

/
6 - 19 Copyright © 2009, Oracle. All rights reserved.

Using INDEX BY Table Methods
The following methods make INDEX BY tables easier to use: • EXISTS • PRIOR • COUNT • NEXT • FIRST and LAST • DELETE

6 - 20

Copyright © 2009, Oracle. All rights reserved.

INDEX BY Table of Records
Define an INDEX BY table variable to hold an entire row from a table. Example:
DECLARE TYPE dept_table_type IS TABLE OF departments%ROWTYPE INDEX BY PLS_INTEGER; dept_table dept_table_type; -- Each element of dept_table is a record

6 - 21

Copyright © 2009, Oracle. All rights reserved.

INDEX BY Table of Records: Example
SET SERVEROUTPUT ON DECLARE TYPE emp_table_type IS TABLE OF employees%ROWTYPE INDEX BY PLS_INTEGER; my_emp_table emp_table_type; max_count NUMBER(3):= 104; BEGIN FOR i IN 100..max_count LOOP SELECT * INTO my_emp_table(i) FROM employees WHERE employee_id = i; END LOOP; FOR i IN my_emp_table.FIRST..my_emp_table.LAST LOOP DBMS_OUTPUT.PUT_LINE(my_emp_table(i).last_name); END LOOP; END; /

6 - 23

Copyright © 2009, Oracle. All rights reserved.

Nested Tables

1 2 3 4 .. 2 GB

Bombay Sydney Oxford London ....

6 - 24

Copyright © 2009, Oracle. All rights reserved.

. Oracle.VARRAY 1 2 3 4 . Tokyo 6 . 10 Bombay Sydney Oxford London .. .26 Copyright © 2009. All rights reserved...

Oracle. . All rights reserved.27 Copyright © 2009.Summary In this lesson. you should have learned how to: • Define and reference PL/SQL variables of composite data types – PL/SQL record – INDEX BY table – INDEX BY table of records • Define a PL/SQL record by using the %ROWTYPE attribute 6 .

Oracle.Practice 6: Overview This practice covers the following topics: • Declaring INDEX BY tables • Processing data by using INDEX BY tables • • Declaring a PL/SQL record Processing data by using a PL/SQL record 6 . All rights reserved.28 Copyright © 2009. .

Oracle.Using Explicit Cursors Copyright © 2009. All rights reserved. .

you should be able to do the following: • Distinguish between implicit and explicit cursors • Discuss the reasons for using explicit cursors • Declare and control explicit cursors • Use simple loops and cursor FOR loops to fetch data • • • Declare and use cursors with parameters Lock rows with the FOR UPDATE clause Reference the current row with the WHERE CURRENT OF clause 7-2 Copyright © 2009.Objectives After completing this lesson. Oracle. . All rights reserved.

. All rights reserved. Oracle.Cursors Every SQL statement executed by the Oracle server has an associated individual cursor: • Implicit cursors: Declared and managed by PL/SQL for all DML and PL/SQL SELECT statements • Explicit cursors: Declared and managed by the programmer 7-3 Copyright © 2009.

. . . 139 Seo 140 Patel . . 7-4 Copyright © 2009. .Explicit Cursor Operations Table 100 King Active set AD_PRES 101 Kochhar AD_VP 102 De Haan AD_VP . . All rights reserved. . . . ST_CLERK ST_CLERK . . Oracle.

7-5 Copyright © 2009. current row into variables.Controlling Explicit Cursors No DECLARE OPEN FETCH EMPTY? Yes CLOSE • Create a • Identify the • Load the named SQL area. All rights reserved. . • Return to FETCH if rows are found. Oracle. • Test for existing rows. • Release the active set. active set.

Cursor pointer 2 Fetch a row. . Oracle.Controlling Explicit Cursors 1 Open the cursor. Cursor pointer 7-6 Copyright © 2009. Cursor pointer 3 Close the cursor. All rights reserved.

. last_name FROM employees WHERE department_id =30. All rights reserved. Examples: DECLARE CURSOR emp_cursor IS SELECT employee_id. Oracle. ..Declaring the Cursor Syntax: CURSOR cursor_name IS select_statement. CURSOR dept_cursor IS SELECT * FROM departments WHERE location_id = locid.. 7-7 Copyright © 2009. DECLARE locid NUMBER:= 1700.

All rights reserved. . 7-9 Copyright © 2009. last_name FROM employees WHERE department_id =30. BEGIN OPEN emp_cursor. ... Oracle.Opening the Cursor DECLARE CURSOR emp_cursor IS SELECT employee_id.

/ 7 .. All rights reserved.. DBMS_OUTPUT.Fetching Data from the Cursor SET SERVEROUTPUT ON DECLARE CURSOR emp_cursor IS SELECT employee_id. FETCH emp_cursor INTO empno. . last_name FROM employees WHERE department_id =30. .last_name%TYPE. lname.PUT_LINE( empno ||' '||lname).10 Copyright © 2009. Oracle. empno employees. BEGIN OPEN emp_cursor. END. lname employees.employee_id%TYPE.

BEGIN OPEN emp_cursor.employee_id%TYPE. lname employees. Oracle.Fetching Data from the Cursor SET SERVEROUTPUT ON DECLARE CURSOR emp_cursor IS SELECT employee_id. EXIT WHEN emp_cursor%NOTFOUND. empno employees.last_name%TYPE.12 Copyright © 2009. END LOOP. .. DBMS_OUTPUT. All rights reserved. last_name FROM employees WHERE department_id =30. LOOP FETCH emp_cursor INTO empno.PUT_LINE( empno ||' '||lname). / 7 . END.. . lname.

LOOP FETCH emp_cursor INTO empno. EXIT WHEN emp_cursor%NOTFOUND. / 7 . All rights reserved.. Oracle. DBMS_OUTPUT..PUT_LINE( empno ||' '||lname). END. . lname. CLOSE emp_cursor.Closing the Cursor . END LOOP.13 Copyright © 2009.

. emp_record emp_cursor%ROWTYPE. DECLARE CURSOR emp_cursor IS SELECT employee_id. last_name FROM employees WHERE department_id =30.14 Copyright © 2009. All rights reserved.. LOOP FETCH emp_cursor INTO emp_record. 7 .Cursors and Records Process the rows of the active set by fetching values into a PL/SQL record. BEGIN OPEN emp_cursor. Oracle. . .

Oracle. statement2. fetch. . • • • The cursor FOR loop is a shortcut to process explicit cursors. Implicit open. and close occur. The record is implicitly declared. 7 . exit.Cursor FOR Loops Syntax: FOR record_name IN cursor_name LOOP statement1. . .15 Copyright © 2009. END LOOP. All rights reserved. .

.last_name).PUT_LINE( emp_record. / 7 .Cursor FOR Loops SET SERVEROUTPUT ON DECLARE CURSOR emp_cursor IS SELECT employee_id. BEGIN FOR emp_record IN emp_cursor LOOP DBMS_OUTPUT. All rights reserved.16 Copyright © 2009. END. END LOOP.employee_id ||' ' ||emp_record. Oracle. last_name FROM employees WHERE department_id =30.

complement of %NOTFOUND Evaluates to the total number of rows returned so far 7 . .Explicit Cursor Attributes Obtain status information about a cursor. Oracle. Attribute %ISOPEN %NOTFOUND %FOUND %ROWCOUNT Type Boolean Boolean Boolean Boolean Description Evaluates to TRUE if the cursor is open Evaluates to TRUE if the most recent fetch does not return a row Evaluates to TRUE if the most recent fetch returns a row. All rights reserved.17 Copyright © 2009.

LOOP FETCH emp_cursor.18 Copyright © 2009. Example: IF NOT emp_cursor%ISOPEN THEN OPEN emp_cursor. Use the %ISOPEN cursor attribute before performing a fetch to test whether the cursor is open.. . All rights reserved..%ISOPEN Attribute • • Fetch rows only when the cursor is open. END IF. Oracle. 7 .

BEGIN OPEN emp_cursor. CURSOR emp_cursor IS SELECT employee_id. ename employees. / 7 . ename. last_name FROM employees.%ROWCOUNT and %NOTFOUND: Example SET SERVEROUTPUT ON DECLARE empno employees. LOOP FETCH emp_cursor INTO empno. END . All rights reserved.19 Copyright © 2009.employee_id%TYPE. EXIT WHEN emp_cursor%ROWCOUNT > 10 OR emp_cursor%NOTFOUND. Oracle. END LOOP.PUT_LINE(TO_CHAR(empno) ||' '|| ename). . CLOSE emp_cursor.last_name%TYPE. DBMS_OUTPUT.

20 Copyright © 2009.PUT_LINE( emp_record. END. All rights reserved. Oracle.Cursor FOR Loops Using Subqueries There is no need to declare the cursor. last_name FROM employees WHERE department_id =30) LOOP DBMS_OUTPUT.employee_id ||' '||emp_record. . END LOOP. Example: SET SERVEROUTPUT ON BEGIN FOR emp_record IN (SELECT employee_id.last_name). / 7 .

Oracle.. 7 . Open an explicit cursor several times with a different active set each time..Cursors with Parameters Syntax: CURSOR cursor_name [(parameter_name datatype. OPEN cursor_name(parameter_value... All rights reserved.21 Copyright © 2009..)] IS select_statement.. .. • • Pass the parameter values to a cursor when the cursor is opened and the query is executed. .) .

. 7 . BEGIN OPEN emp_cursor (10). dept_id NUMBER..Cursors with Parameters SET SERVEROUTPUT ON DECLARE CURSOR emp_cursor (deptno NUMBER) IS SELECT employee_id.. CLOSE emp_cursor.. . OPEN emp_cursor (20).22 Copyright © 2009. . Oracle. lname VARCHAR2(15). last_name FROM employees WHERE department_id = deptno.. All rights reserved.

• • Use explicit locking to deny access to other sessions for the duration of a transaction.. Oracle. . FROM .23 Copyright © 2009. Lock the rows before the update or delete. All rights reserved.FOR UPDATE Clause Syntax: SELECT . 7 . FOR UPDATE [OF column_reference][NOWAIT | WAIT n]....

WHERE CURRENT OF emp_cursor.25 Copyright © 2009.. .WHERE CURRENT OF Clause Syntax: WHERE CURRENT OF cursor . UPDATE employees SET salary = . All rights reserved. • • • Use cursors to update or delete the current row.. Include the FOR UPDATE clause in the cursor query to lock the rows first. 7 . Use the WHERE CURRENT OF clause to reference the current row from an explicit cursor. Oracle.

staff >= 3.staff FROM departments t1. ..26 Copyright © 2009. t1. All rights reserved.department_id AND t2.Cursors with Subqueries Example: DECLARE CURSOR my_cursor IS SELECT t1.department_name. 7 . COUNT(*) AS staff FROM employees GROUP BY department_id) t2 WHERE t1. . t2. (SELECT department_id.department_id.department_id = t2. Oracle..

Oracle. – Explicit cursors are used for queries of zero.27 Copyright © 2009. . or more rows. • • • • Create and handle explicit cursors Use simple loops and cursor FOR loops to handle multiple rows in the cursors Evaluate the cursor status by using the cursor attributes Use the FOR UPDATE and WHERE CURRENT OF clauses to update or delete the current fetched row 7 . All rights reserved. you should have learned how to: • Distinguish cursor types: – Implicit cursors are used for all DML statements and singlerow queries.Summary In this lesson. one.

Oracle.28 Copyright © 2009. .Practice 7: Overview This practice covers the following topics: • Declaring and using explicit cursors to query rows of a table • Using a cursor FOR loop • • • Applying cursor attributes to test the cursor status Declaring and using cursors with parameters Using the FOR UPDATE and WHERE CURRENT OF clauses 7 . All rights reserved.

Handling Exceptions Copyright © 2009. . All rights reserved. Oracle.

Oracle. .Objectives After completing this lesson. you should be able to do the following: • Define PL/SQL exceptions • Recognize unhandled exceptions • List and use different types of PL/SQL exception handlers • Trap unanticipated errors • Describe the effect of exception propagation in nested blocks • Customize PL/SQL exception messages 8-2 Copyright © 2009. All rights reserved.

All rights reserved.PUT_LINE ('John''s last name is : ' ||lname). BEGIN SELECT last_name INTO lname FROM employees WHERE first_name='John'. DBMS_OUTPUT. Oracle.Example of an Exception SET SERVEROUTPUT ON DECLARE lname VARCHAR2(15). / 8-3 Copyright © 2009. . END.

PUT_LINE (' Your select statement retrieved multiple rows.PUT_LINE ('John''s last name is : ' ||lname). / 8-4 Copyright © 2009.'). Consider using a cursor. DBMS_OUTPUT. END. BEGIN SELECT last_name INTO lname FROM employees WHERE first_name='John'. Oracle.Example of an Exception SET SERVEROUTPUT ON DECLARE lname VARCHAR2(15). All rights reserved. . EXCEPTION WHEN TOO_MANY_ROWS THEN DBMS_OUTPUT.

. All rights reserved. An exception can be raised: – Implicitly by the Oracle server – Explicitly by the program • An exception can be handled: – By trapping it with a handler – By propagating it to the calling environment 8-5 Copyright © 2009.Handling Exceptions with PL/SQL • • An exception is a PL/SQL error that is raised during program execution. Oracle.

section. Propagate the exception. 8-6 Copyright © 2009. Exception Execute statements in the EXCEPTION is raised. All rights reserved. Terminate gracefully.Handling Exceptions Is the exception trapped? Yes No Terminate abruptly. Oracle. .

All rights reserved. .Exception Types • • Predefined Oracle server Non-predefined Oracle server } Implicitly raised • User-defined Explicitly raised 8-7 Copyright © 2009. Oracle.

. All rights reserved. . [WHEN exception3 [OR exception4 . .] THEN statement1. . . . statement2.] THEN statement1. .Trapping Exceptions Syntax: EXCEPTION WHEN exception1 [OR exception2 . statement2. . . .] 8-8 Copyright © 2009. . Oracle. statement2. . . .] [WHEN OTHERS THEN statement1.

Guidelines for Trapping Exceptions • • • • The EXCEPTION keyword starts the exception handling section. All rights reserved. . 8 . Only one handler is processed before leaving the block. Oracle. WHEN OTHERS is the last clause. Several exception handlers are allowed.10 Copyright © 2009.

All rights reserved.11 Copyright © 2009. . Sample predefined exceptions: – – – – – NO_DATA_FOUND TOO_MANY_ROWS INVALID_CURSOR ZERO_DIVIDE DUP_VAL_ON_INDEX 8 .Trapping Predefined Oracle Server Errors • • Reference the predefined name in the exception-handling routine. Oracle.

Oracle. Use PRAGMA EXCEPTION_INIT. . Declarative section Name the exception. All rights reserved.Trapping Non-Predefined Oracle Server Errors Declare Associate Reference EXCEPTION section Handle the raised exception.14 Copyright © 2009. 8 .

NULL). -01400). BEGIN INSERT INTO departments (department_id. DBMS_OUTPUT. PRAGMA EXCEPTION_INIT (insert_excep.PUT_LINE('INSERT OPERATION FAILED'). department_name) VALUES (280. Oracle.Non-Predefined Error To trap Oracle server error number –01400 (“cannot insert NULL”): SET SERVEROUTPUT ON DECLARE insert_excep EXCEPTION. EXCEPTION WHEN insert_excep THEN DBMS_OUTPUT. / 1 2 3 8 . All rights reserved.15 Copyright © 2009.PUT_LINE(SQLERRM). . END.

.16 Copyright © 2009.Functions for Trapping Exceptions • • SQLCODE: Returns the numeric value for the error code SQLERRM: Returns the message associated with the error number 8 . Oracle. All rights reserved.

/ 8 .. EXCEPTION .. All rights reserved..17 Copyright © 2009. INSERT INTO errors (e_user. error_code := SQLCODE . BEGIN . e_date. error_message) VALUES(USER. error_message).. Oracle.Functions for Trapping Exceptions Example: DECLARE error_code NUMBER.SYSDATE. error_message VARCHAR2(255). error_code. . error_message := SQLERRM . END.error_code. WHEN OTHERS THEN ROLLBACK.

. 8 . Raise Executable section Explicitly raise the exception by using the RAISE statement.18 Copyright © 2009.Trapping User-Defined Exceptions Declare Declarative section Name the exception. Reference Exception-handling section Handle the raised exception. Oracle. All rights reserved.

Trapping User-Defined Exceptions ACCEPT deptno PROMPT 'Please enter the department number:' ACCEPT name PROMPT 'Please enter the department name:' DECLARE invalid_department EXCEPTION. deptno NUMBER :=&deptno. . Oracle. 3 EXCEPTION WHEN invalid_department THEN DBMS_OUTPUT. IF SQL%NOTFOUND THEN RAISE invalid_department. BEGIN UPDATE departments SET department_name = name WHERE department_id = deptno. 1 name VARCHAR2(20):='&name'. COMMIT.'). / 8 . All rights reserved. 2 END IF.PUT_LINE('No such department id. END.19 Copyright © 2009.

All rights reserved. Oracle. .20 Copyright © 2009.Calling Environments SQL*Plus SQL Developer Oracle Developer Forms Precompiler application An enclosing PL/SQL block Displays error number and message to screen Displays error number and message to screen Accesses error number and message in an ON-ERROR trigger by means of the ERROR_CODE and ERROR_TEXT packaged functions Accesses the exception number through the SQLCA data structure Traps the exception in exception-handling routine of enclosing block 8 .

. .. / Subblocks can handle an exception or pass the exception to the enclosing block. All rights reserved.. END IF. END..Propagating Exceptions in a Subblock DECLARE . 8 .. PRAGMA EXCEPTION_INIT (integrity. no_rows exception. Oracle. END LOOP.21 Copyright © 2009.. -2292). BEGIN FOR c_record IN emp_cursor LOOP BEGIN SELECT .. UPDATE . IF SQL%NOTFOUND THEN RAISE no_rows. END. EXCEPTION WHEN integrity THEN . . integrity exception. . WHEN no_rows THEN ..

22 Copyright © 2009. {TRUE | FALSE}]). • • You can use this procedure to issue user-defined error messages from stored subprograms. . All rights reserved. You can report errors to your application and avoid returning unhandled exceptions. 8 .RAISE_APPLICATION_ERROR Procedure Syntax: raise_application_error (error_number. Oracle. message[.

23 Copyright © 2009.RAISE_APPLICATION_ERROR Procedure • Used in two different places: – Executable section – Exception section • Returns error conditions to the user in a manner consistent with other Oracle server errors 8 . . Oracle. All rights reserved.

DELETE FROM employees WHERE manager_id = v_mgr. IF SQL%NOTFOUND THEN RAISE_APPLICATION_ERROR(-20202.. . Oracle.RAISE_APPLICATION_ERROR Procedure Executable section: BEGIN . / 8 .24 Copyright © 2009.. 'Manager is not a valid employee. END. Exception section: .. .. EXCEPTION WHEN NO_DATA_FOUND THEN RAISE_APPLICATION_ERROR (-20201..'). All rights reserved. END IF.. 'This is not a valid manager').

Summary In this lesson.25 Copyright © 2009. All rights reserved. . Oracle. you should have learned how to: • Define PL/SQL exceptions • Add an EXCEPTION section to the PL/SQL block to deal with exceptions at run time • Handle different types of exceptions: – Predefined exceptions – Non-predefined exceptions – User-defined exceptions • Propagate exceptions in nested blocks and call applications 8 .

Oracle. .26 Copyright © 2009.Practice 8: Overview This practice covers the following topics: • Handling named exceptions • Creating and invoking user-defined exceptions 8 . All rights reserved.

.Creating Stored Procedures and Functions Copyright © 2009. All rights reserved. Oracle.

. All rights reserved. you should be able to do the following: • Differentiate between anonymous blocks and subprograms • Create a simple procedure and invoke it from an anonymous block • Create a simple function • Create a simple function that accepts a parameter • Differentiate between procedures and functions 9-2 Copyright © 2009.Objectives After completing this lesson. Oracle.

Procedures and Functions • • • Are named PL/SQL blocks Are called PL/SQL subprograms Have block structures similar to anonymous blocks: – Optional declarative section (without DECLARE keyword) – Mandatory executable section – Optional section to handle exceptions 9-3 Copyright © 2009. Oracle. All rights reserved. .

All rights reserved. .Differences Between Anonymous Blocks and Subprograms Anonymous Blocks Unnamed PL/SQL blocks Compiled every time Not stored in the database Cannot be invoked by other applications Do not return values Subprograms Named PL/SQL blocks Compiled only once Stored in the database Named and. therefore. Oracle. Can take parameters Cannot take parameters 9-4 Copyright © 2009. can be invoked by other applications Subprograms called functions must return values.

. . All rights reserved. Oracle.Procedure: Syntax CREATE [OR REPLACE] PROCEDURE procedure_name [(argument1 [mode1] datatype1.)] IS|AS procedure_body. 9-5 Copyright © 2009. . argument2 [mode2] datatype2. .

PUT_LINE(' Inserted '|| SQL%ROWCOUNT ||' row '). BEGIN dept_id:=280.department_name) VALUES(dept_id. END. All rights reserved. . CREATE PROCEDURE add_dept IS dept_id dept.department_id%TYPE.Procedure: Example CREATE TABLE dept AS SELECT * FROM departments. / 9-6 Copyright © 2009. dept_name:='ST-Curriculum'.department_name%TYPE. dept_name dept.dept_name). INSERT INTO dept(department_id. Oracle. DBMS_OUTPUT.

. Oracle. END.Invoking the Procedure BEGIN add_dept. 9-8 Copyright © 2009. All rights reserved. department_name FROM dept WHERE department_id=280. / SELECT department_id.

. . . Oracle.Function: Syntax CREATE [OR REPLACE] FUNCTION function_name [(argument1 [mode1] datatype1. . argument2 [mode2] datatype2.)] RETURN datatype IS|AS function_body. 9-9 Copyright © 2009. All rights reserved.

Function: Example CREATE FUNCTION check_sal RETURN Boolean IS dept_id employees. empno employees.10 Copyright © 2009.department_id%TYPE.employee_id%TYPE. sal employees. SELECT salary.dept_id FROM employees WHERE employee_id= empno. Oracle. / 9 .salary%TYPE.salary%TYPE. ELSE RETURN FALSE. avg_sal employees.department_id INTO sal. END. . All rights reserved. SELECT avg(salary) INTO avg_sal FROM employees WHERE department_id=dept_id. EXCEPTION WHEN NO_DATA_FOUND THEN RETURN NULL. BEGIN empno:=205. IF sal > avg_sal THEN RETURN TRUE. END IF.

PUT_LINE('Salary > average'). Oracle. ELSE DBMS_OUTPUT.Invoking the Function SET SERVEROUTPUT ON BEGIN IF (check_sal IS NULL) THEN DBMS_OUTPUT.11 Copyright © 2009. / 9 .PUT_LINE('The function returned NULL due to exception').PUT_LINE('Salary < average'). END IF. All rights reserved. . ELSIF (check_sal) THEN DBMS_OUTPUT. END.

END IF. SELECT avg(salary) INTO avg_sal FROM employees WHERE department_id=dept_id.. ..salary%TYPE. 9 . ELSE RETURN FALSE..salary%TYPE.employee_id%TYPE) RETURN Boolean IS dept_id employees..dept_id FROM employees WHERE employee_id=empno. BEGIN SELECT salary.Passing a Parameter to the Function DROP FUNCTION check_sal. CREATE FUNCTION check_sal(empno employees. EXCEPTION .12 Copyright © 2009. IF sal > avg_sal THEN RETURN TRUE. Oracle. sal employees. avg_sal employees.department_id%TYPE.department_id INTO sal. All rights reserved. .

PUT_LINE('The function returned NULL due to exception'). Oracle.PUT_LINE('Checking for employee with id 70').. DBMS_OUTPUT.PUT_LINE('Checking for employee with id 205').PUT_LINE('Salary > average'). END.PUT_LINE('The function returned NULL due to exception'). All rights reserved. IF (check_sal(205) IS NULL) THEN DBMS_OUTPUT.Invoking the Function with a Parameter BEGIN DBMS_OUTPUT. END IF. ELSIF (check_sal(70)) THEN . IF (check_sal(70) IS NULL) THEN DBMS_OUTPUT. ELSE DBMS_OUTPUT. END IF.13 Copyright © 2009. . / PUT THE SCREENSHOT OF OUTPUT HERE 9 .PUT_LINE('Salary < average').. ELSIF (check_sal(205)) THEN DBMS_OUTPUT.

Summary In this lesson. you should have learned how to: • Create a simple procedure • Invoke the procedure from an anonymous block • Create a simple function • Create a simple function that accepts parameters • Invoke the function from an anonymous block 9 . . All rights reserved.14 Copyright © 2009. Oracle.

All rights reserved.15 Copyright © 2009. Oracle.Practice 9: Overview This practice covers the following topics: • Converting an existing anonymous block to a procedure • Modifying the procedure to accept a parameter • Writing an anonymous block to invoke the procedure 9 . .

REF Cursors Copyright © 2009. Oracle. . All rights reserved.

Cursor variables give you more flexibility. a pointer is declared as REF X. but a cursor variable is dynamic. A cursor variable has the data type REF CURSOR. where REF is short for REFERENCE and X stands for a class of objects.Cursor Variables • Cursor variables are like C or Pascal pointers. Oracle. • • • • C-2 Copyright © 2009. All rights reserved. which hold the memory location (address) of an item instead of the item itself. In PL/SQL. . A cursor is static.

C-3 Copyright © 2009. . All rights reserved. You can pass the value of a cursor variable freely from one scope to another.Why Use Cursor Variables? • • • • You can use cursor variables to pass query result sets between PL/SQL stored subprograms and various clients. You can reduce network traffic by having a PL/SQL block open (or close) several host cursor variables in a single round trip. PL/SQL can share a pointer to the query work area in which the result set is stored. Oracle.

Oracle. C-4 Copyright © 2009. . • Example: DECLARE TYPE DeptCurTyp IS REF CURSOR RETURN departments%ROWTYPE.Defining REF CURSOR Types • Define a REF CURSOR type: Define a REF CURSOR type TYPE ref_type_name IS REF CURSOR [RETURN return_type]. dept_cv DeptCurTyp. All rights reserved. • Declare a cursor variable of that type: ref_cv ref_type_name.

FETCH. All rights reserved. The FETCH statement returns a row from the result set of a multirow query. and advances the cursor to the next row. and positions the cursor to point to the first row of the result set. Oracle. The CLOSE statement disables a cursor variable.Using the OPEN-FOR. • • C-7 Copyright © 2009. identifies the result set. and CLOSE Statements • The OPEN-FOR statement associates a cursor variable with a multirow query. increments the count kept by %ROWCOUNT. executes the query. assigns the values of select-list items to corresponding variables or fields in the INTO clause. .

BEGIN sql_stmt := 'SELECT * FROM employees WHERE job_id = :j'.An Example of Fetching DECLARE TYPE EmpCurTyp IS REF CURSOR. / C . CLOSE emp_cv. LOOP FETCH emp_cv INTO emp_rec. Oracle. . All rights reserved. OPEN emp_cv FOR sql_stmt USING my_job. EXIT WHEN emp_cv%NOTFOUND. -. emp_rec employees%ROWTYPE. emp_cv EmpCurTyp. sql_stmt VARCHAR2(200).10 Copyright © 2009.process record END LOOP. END. my_job VARCHAR2(10) := 'ST_CLERK'.

. Oracle. All rights reserved.Oracle JDeveloper Copyright © 2009.

Oracle JDeveloper 10g D-2 Copyright © 2009. All rights reserved. . Oracle.

Oracle. All rights reserved.Connection Navigator D-3 Copyright © 2009. .

Application Navigator D-4 Copyright © 2009. Oracle. All rights reserved. .

All rights reserved. Oracle. .Structure Window D-5 Copyright © 2009.

Editor Window D-6 Copyright © 2009. . All rights reserved. Oracle.

Create a deployment profile. 2. Oracle. Create a database connection. perform the following steps: 1. All rights reserved. 3. 1 2 3 D-7 Copyright © 2009. Deploy the objects. .Deploying Java Stored Procedures Before deploying Java stored procedures.

Oracle.Creating Program Units Skeleton of the function D-8 Copyright © 2009. All rights reserved. .

. All rights reserved.Compiling Compilation with errors Compilation without errors D-9 Copyright © 2009. Oracle.

All rights reserved. Oracle.10 Copyright © 2009. .Running a Program Unit D .

Oracle.11 Copyright © 2009. All rights reserved.Dropping a Program Unit D . .

Debugging PL/SQL Programs
• JDeveloper support two types of debugging:
– Local – Remote

You need the following privileges to perform PL/SQL debugging:
– DEBUG ANY PROCEDURE – DEBUG CONNECT SESSION

D - 12

Copyright © 2009, Oracle. All rights reserved.

Debugging PL/SQL Programs

D - 13

Copyright © 2009, Oracle. All rights reserved.

Setting Breakpoints

D - 15

Copyright © 2009, Oracle. All rights reserved.

Stepping Through Code
Debug

D - 16

Copyright © 2009, Oracle. All rights reserved.

Using SQL Developer

Copyright © 2009, Oracle. All rights reserved.

Objectives After completing this appendix. All rights reserved. you should be able to do the following: • List the key features of Oracle SQL Developer • Install Oracle SQL Developer • Identify menu items of Oracle SQL Developer • Create a database connection • Manage database objects • Use SQL Worksheet • Execute SQL statements and SQL scripts • Create and save reports E-2 Copyright © 2009. . Oracle.

What Is Oracle SQL Developer? • Oracle SQL Developer is a free graphical tool that enhances productivity and simplifies database development tasks. • E-3 Copyright © 2009. Oracle. All rights reserved. You can connect to any target Oracle database schema by using standard Oracle database authentication. .

1 and later Is bundled with JRE 1.Key Features • • • • • • Was developed in Java Supports Windows. All rights reserved. . Oracle. and Mac OS X platforms Uses the JDBC Thin driver for default connectivity Does not require an installer Connects to any Oracle Database version 9.5 E-4 Copyright © 2009. Linux.2.0.

Oracle. All rights reserved. . E-5 Copyright © 2009.Installing SQL Developer Download the Oracle SQL Developer kit and unzip into any directory on your machine.

All rights reserved. .Menus for SQL Developer 2 1 3 4 5 6 7 E-6 Copyright © 2009. Oracle.

Each additional database connection created is listed in the connections navigator hierarchy. . Oracle.ora file on your system.Creating a Database Connection • • You must have at least one database connection to use SQL Developer. E-7 Copyright © 2009. You can create and test connections: – For multiple databases – For multiple schemas • • • SQL Developer automatically imports any connections defined in the tnsnames. You can export connections to an XML file. All rights reserved.

Oracle. All rights reserved. .Creating a Database Connection E-8 Copyright © 2009.

Oracle.Browsing Database Objects Use the Database Navigator to: • Browse through many objects in a database schema • Do a quick review of the definitions of objects E-9 Copyright © 2009. All rights reserved. .

All rights reserved. . You can view the DDL for adjustments such as creating a new object or editing an existing schema object.Creating a Schema Object • SQL Developer supports the creation of any schema object by: – Executing a SQL statement in SQL Worksheet – Using the context menu • • You can edit the objects by using an edit dialog box or one of the many context-sensitive menus. E .10 Copyright © 2009. Oracle.

11 Copyright © 2009. . Oracle.Creating a New Table: Example E . All rights reserved.

PL/SQL. E . and SQL*Plus statements. . All rights reserved.Using SQL Worksheet • • Use SQL Worksheet to enter and execute SQL.12 Copyright © 2009. Specify any actions that can be processed by the database connection associated with the worksheet. Oracle.

Using SQL Worksheet 2 4 6 1 3 5 7 8 E .13 Copyright © 2009. All rights reserved. . Oracle.

14 Copyright © 2009. All rights reserved. E .Executing SQL Statements Use the Enter SQL Statement box to enter single or multiple SQL statements. . Oracle.

All rights reserved. Oracle. .15 Copyright © 2009.Viewing the Execution Plan E .

Formatting the SQL Code Before Formatting After Formatting E . Oracle.16 Copyright © 2009. All rights reserved. .

All rights reserved. Oracle. E .Using Snippets Snippets are code fragments that may be just syntax or examples.17 Copyright © 2009. .

.Using Snippets: Example Inserting a snippet Editing the snippet E . All rights reserved. Oracle.18 Copyright © 2009.

Creating an Anonymous Block Create an anonymous block and display the output of DBMS_OUTPUT package statements. E .19 Copyright © 2009. All rights reserved. . Oracle.

Editing the PL/SQL Code Use the full-featured editor for PL/SQL program units: E . Oracle. All rights reserved.20 Copyright © 2009. .

21 Copyright © 2009. . All rights reserved.Creating a PL/SQL Procedure 1 2 E . Oracle.

22 Copyright © 2009. All rights reserved. Oracle. . SQL*Plus statements that are not supported by SQL Worksheet are: – – – – – – append archive attribute break change clear E .Using SQL*Plus • • SQL Worksheet does not support all SQL*Plus statements.

You can create your own customized reports too. The Reports are organized into categories. All rights reserved. Oracle.Database Reporting • • • SQL Developer provides you with a number of predefined reports about your database and objects. . E .23 Copyright © 2009.

All rights reserved. E .Creating a User-Defined Report Create and save user-defined reports for repeated use.24 Copyright © 2009. Oracle. .

Summary In this appendix. you should have learned how to use SQL Developer to do the following: • Browse. All rights reserved. and edit database objects • Execute SQL statements and scripts in SQL Worksheet • Create and save custom reports E .25 Copyright © 2009. Oracle. create. .