Introduction to PL/SQL Copyright © 2009, Oracle. All rights reserved. Objectives After completing this lesson, 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 • Output messages in PL/SQL 1-2 Copyright © 2009, Oracle. All rights reserved. About 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, Oracle. All rights reserved. About PL/SQL PL/SQL: • Provides a block structure for executable units of code. Maintenance of code is made easier with such a welldefined structure. • Provides procedural constructs such as: – Variables, constants, and data types – Control structures such as conditional statements and loops – Reusable program units that are written once and executed many times 1-4 Copyright © 2009, Oracle. All rights reserved. PL/SQL Run-Time Architecture PL/SQL block procedural PL/SQL SQL Procedural statement executor PL/SQL Engine Oracle Server SQL statement executor 1-5 Copyright © 2009, Oracle. All rights reserved. PL/SQL Block Structure • DECLARE (optional) – Variables, cursors, user-defined exceptions • BEGIN (mandatory) – SQL statements – PL/SQL statements • EXCEPTION (optional) – Actions to perform when exceptions occur • 1-6 END; (mandatory) Copyright © 2009, Oracle. All rights reserved. Block Types Procedure Function PROCEDURE name IS [DECLARE] [EXCEPTION] FUNCTION name RETURN datatype IS BEGIN --statements RETURN value; [EXCEPTION] END; END; END; BEGIN --statements 1-7 Copyright © 2009, Oracle. All rights reserved. Anonymous BEGIN --statements [EXCEPTION] Examining an Anonymous Block An anonymous block in the SQL Developer workspace: 1-8 Copyright © 2009, Oracle. All rights reserved. Executing an Anonymous Block Click the Run Script button to execute the anonymous block: Run Script (or F5) 1-9 Copyright © 2009, Oracle. All rights reserved. Agenda • • • 1 - 10 Understanding the benefits and structure of PL/SQL Examining PL/SQL blocks Generating output messages in PL/SQL Copyright © 2009, Oracle. All rights reserved. Enabling Output of a PL/SQL Block 1. To enable output in SQL Developer, execute the following command before running the PL/SQL block: SET SERVEROUTPUT ON 2. Use a predefined Oracle package and its procedure in the anonymous block: – DBMS_OUTPUT.PUT_LINE DBMS_OUTPUT.PUT_LINE(' The First Name of the Employee is ' || v_fname); … 1 - 11 Copyright © 2009, Oracle. All rights reserved. Viewing the Output of a PL/SQL Block Press F5 to execute the command and PL/SQL block. 1 - 12 Copyright © 2009, Oracle. All rights reserved. Declaring PL/SQL Variables Copyright © 2009, Oracle. All rights reserved. Use of Variables Variables can be used for: • Temporary storage of data • Manipulation of stored values • Reusability SELECT first_name, department_id INTO v_fname, v_deptno FROM … 1 - 14 Jennifer Copyright © 2009, Oracle. All rights reserved. 10 v_fname v_deptno Requirements for Variable Names A variable name: • Must start with a letter • Can include letters or numbers • Can include special characters (such as $, _, and #) • • 1 - 15 Must contain no more than 30 characters Must not include reserved words Copyright © 2009, Oracle. All rights reserved. Declaring and Initializing PL/SQL Variables Syntax: identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr]; Examples: DECLARE v_hiredate v_deptno v_location c_comm 1 - 16 DATE; NUMBER(2) NOT NULL := 10; VARCHAR2(13) := 'Atlanta'; CONSTANT NUMBER := 1400; Copyright © 2009, Oracle. All rights reserved. Declaring and Initializing PL/SQL Variables 1 2 1 - 17 DECLARE v_myName VARCHAR2(20); BEGIN DBMS_OUTPUT.PUT_LINE('My name is: '|| v_myName); v_myName := 'John'; DBMS_OUTPUT.PUT_LINE('My name is: '|| v_myName); END; / DECLARE v_myName VARCHAR2(20):= 'John'; BEGIN v_myName := 'Steven'; DBMS_OUTPUT.PUT_LINE('My name is: '|| v_myName); END; / Copyright © 2009, Oracle. All rights reserved. Types of Variables • PL/SQL variables: – Scalar (Basic) – Boolean – Large object (LOB) – Composite (cursors, records , array) 1 - 18 Copyright © 2009, Oracle. All rights reserved. Types of Variables 15-JAN-09 TRUE/ FALSE Snow White Long, long ago, in a land far, far away, there lived a princess called Snow White. . . Atlanta 256120.08 1 - 19 Copyright © 2009, Oracle. All rights reserved. Guidelines for Declaring and Initializing PL/SQL Variables • • • • Follow consistent naming conventions. Use meaningful identifiers for variables. Initialize variables that are designated as NOT NULL and CONSTANT. Initialize variables with the assignment operator (:=) or the DEFAULT keyword: v_myName VARCHAR2(20):='John'; v_myName VARCHAR2(20) DEFAULT 'John'; • Declare one identifier per line for better readability and code maintenance. 1 - 20 Copyright © 2009, Oracle. All rights reserved. Guidelines for Declaring 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; / • 1 - 21 Use the NOT NULL constraint when the variable must hold a value. Copyright © 2009, Oracle. All rights reserved. Naming Conventions of PL/SQL Structures Used in This Course PL/SQL Structure Convention Example Variable v_variable_name v_rate Constant c_constant_name c_rate Subprogram parameter p_parameter_name p_id Bind (host) variable b_bind_name b_salary Cursor c_cursor_name cur_emp Record rec_record_name rec_emp Type type_name_type ename_table_type Exception e_exception_name e_products_invalid File handle f_file_handle_name f_file 1 - 22 Copyright © 2009, Oracle. All rights reserved. Scalar Data Types • • Hold a single value Have no internal components TRUE 15-JAN-09 The soul of the lazy man desires, and he has nothing; but the soul of the diligent shall be made rich. 256120.08 1 - 23 Atlanta Copyright © 2009, Oracle. All rights reserved. Base Scalar Data Types • • • • • • • • 1 - 24 CHAR [(maximum_length)] VARCHAR (maximum_length) NUMBER [(precision, scale)] BINARY_INTEGER PLS_INTEGER BOOLEAN TRUE FALSE BINARY_FLOAT BINARY_DOUBLE Copyright © 2009, Oracle. All rights reserved. Base Scalar Data Types • • • • • • 1 - 25 DATE TIMESTAMP TIMESTAMP WITH TIME ZONE TIMESTAMP WITH LOCAL TIME ZONE INTERVAL YEAR TO MONTH INTERVAL DAY TO SECOND Copyright © 2009, Oracle. All rights reserved. Declaring Scalar Variables Examples: DECLARE v_emp_job v_count_loop v_dept_total_sal v_orderdate c_tax_rate v_valid ... 1 - 26 VARCHAR2(9); BINARY_INTEGER := 0; NUMBER(9,2) := 0; DATE := SYSDATE + 7; CONSTANT NUMBER(3,2) := 8.25; BOOLEAN NOT NULL := TRUE; Copyright © 2009, Oracle. All rights reserved. %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 name – The name of the declared variable 1 - 27 Copyright © 2009, Oracle. All rights reserved. Declaring Variables with the %TYPE Attribute Syntax identifier table.column_name%TYPE; Examples ... v_emp_lname ... employees.last_name%TYPE; ... v_balance v_min_balance ... NUMBER(7,2); v_balance%TYPE := 1000; 1 - 28 Copyright © 2009, Oracle. All rights reserved. Declaring Boolean Variables • • • • 1 - 29 Only the TRUE, FALSE, and NULL values can be assigned to a Boolean variable. Conditional expressions use the logical operators AND and OR, and the unary operator NOT to check the variable values. The variables always yield TRUE, FALSE, or NULL. Arithmetic, character, and date expressions can be used to return a Boolean value. Copyright © 2009, Oracle. All rights reserved. LOB Data Type Variables Book (CLOB) Photo (BLOB) Movie (BFILE) NCLOB 1 - 30 Copyright © 2009, Oracle. All rights reserved. Composite Data Types: Records and Collections V_comp_orddtl.orderdate TRUE 23-DEC-98 ATLANTA PL/SQL Collections: 1 2 3 4 SMITH JONES NANCY TIM 1 2 3 4 5000 2345 12 3456 NUMBER VARCHAR2 PLS_INTEGER 1 - 31 PLS_INTEGER Copyright © 2009, Oracle. All rights reserved. Writing Executable Statements Copyright © 2009, Oracle. All rights reserved. Lexical Units in a PL/SQL Block Lexical units: • Are building blocks of any PL/SQL block • Are sequences of characters including letters, numerals, tabs, spaces, returns, and symbols • Can be classified as: – – – – 1 - 33 Identifiers: v_fname, c_percent Delimiters: ; , +, Literals: John, 428, True Comments: --, /* */ Copyright © 2009, Oracle. All rights reserved. Commenting Code • • Prefix single-line comments with two hyphens (--). Place a block comment between the symbols /* and */. Example: DECLARE ... v_annual_sal NUMBER (9,2); BEGIN /* Compute the annual salary based on the monthly salary input from the user */ v_annual_sal := monthly_sal * 12; --The following line displays the annual salary DBMS_OUTPUT.PUT_LINE(v_annual_sal); END; / 1 - 34 Copyright © 2009, Oracle. All rights reserved. SQL Functions in PL/SQL • Available in procedural statements: – Single-row functions • Not available in procedural statements: – DECODE – Group functions 1 - 35 Copyright © 2009, Oracle. All rights reserved. SQL Functions in PL/SQL: Examples • Get the length of a string: v_desc_size INTEGER(5); v_prod_description VARCHAR2(70):='You can use this product with your radios for higher frequency'; -- get the length of the string in prod_description v_desc_size:= LENGTH(v_prod_description); • Get the number of months an employee has worked: v_tenure:= MONTHS_BETWEEN (CURRENT_DATE, v_hiredate); 1 - 36 Copyright © 2009, Oracle. 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 1 - 37 Copyright © 2009, Oracle. All rights reserved. Indenting Code For clarity, indent each level of code. BEGIN IF x=0 THEN y:=1; END IF; END; / 1 - 38 DECLARE deptno NUMBER(4); location_id NUMBER(4); BEGIN SELECT department_id, location_id INTO deptno, location_id FROM departments WHERE department_name = 'Sales'; ... END; / Copyright © 2009, Oracle. All rights reserved. Interacting with Oracle Database Server: SQL Statements in PL/SQL Programs Copyright © 2009, Oracle. All rights reserved. Objectives After completing this lesson, you should be able to do the following: • Determine the SQL statements that 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 • Make use of the INTO clause to hold the values returned by a SQL statement • Differentiate between implicit cursors and explicit cursors • Use SQL cursor attributes 1 - 40 Copyright © 2009, Oracle. All rights reserved. SQL Statements in PL/SQL • • • 1 - 41 Retrieve a row from the database by using the SELECT command. Make changes to rows in the database by using DML commands. Control a transaction with the COMMIT, ROLLBACK, or SAVEPOINT command. Copyright © 2009, Oracle. All rights reserved. SELECT Statements in PL/SQL Retrieve data from the database with a SELECT statement. Syntax: SELECT INTO FROM [WHERE 1 - 42 select_list {variable_name[, variable_name]... | record_name} table condition]; Copyright © 2009, Oracle. All rights reserved. SELECT Statements in PL/SQL • The INTO clause is required. • Queries must return only one row. DECLARE v_fname VARCHAR2(25); BEGIN SELECT first_name INTO v_fname FROM employees WHERE employee_id=200; DBMS_OUTPUT.PUT_LINE(' First Name is : '||v_fname); END; / 1 - 43 Copyright © 2009, Oracle. All rights reserved. Retrieving Data in PL/SQL: Example Retrieve hire_date and salary for the specified employee. DECLARE v_emp_hiredate employees.hire_date%TYPE; v_emp_salary employees.salary%TYPE; BEGIN SELECT hire_date, salary INTO v_emp_hiredate, v_emp_salary FROM employees WHERE employee_id = 100; DBMS_OUTPUT.PUT_LINE ('Hire date is :'|| v_emp_hiredate); DBMS_OUTPUT.PUT_LINE ('Salary is :'|| v_emp_ salary); END; / 1 - 44 Copyright © 2009, Oracle. All rights reserved. Retrieving Data in PL/SQL Return the sum of salaries for all the employees in the specified department. Example: DECLARE v_sum_sal NUMBER(10,2); v_deptno NUMBER NOT NULL := 60; BEGIN SELECT SUM(salary) -- group function INTO v_sum_sal FROM employees WHERE department_id = v_deptno; DBMS_OUTPUT.PUT_LINE ('The sum of salary is ' || v_sum_sal); END; 1 - 45 Copyright © 2009, Oracle. All rights reserved. Naming Ambiguities DECLARE v_hire_date employees.hire_date%TYPE; v_sysdate hire_date%TYPE; v_employee_id employees.employee_id%TYPE := 176; BEGIN SELECT hire_date, sysdate INTO v_hire_date, v_sysdate FROM employees WHERE employee_id = employee_id; END; / 1 - 46 Copyright © 2009, Oracle. All rights reserved. Naming Conventions • • • • • 1 - 47 Use a naming convention to avoid ambiguity in the WHERE clause. Avoid using database column names as identifiers. Syntax errors can arise because PL/SQL checks the database first for a column in the table. The names of local variables and formal parameters take precedence over the names of database tables. The names of database table columns take precedence over the names of local variables. Copyright © 2009, Oracle. All rights reserved. Using PL/SQL to Manipulate Data Make changes to database tables by using DML commands: • INSERT • UPDATE • DELETE DELETE • MERGE INSERT UPDATE 1 - 48 MERGE Copyright © 2009, Oracle. All rights reserved. Inserting Data: Example Add new employee information to the EMPLOYEES table. BEGIN INSERT INTO employees (employee_id, first_name, last_name, email, hire_date, job_id, salary) VALUES(employees_seq.NEXTVAL, 'Ruth', 'Cores', 'RCORES',CURRENT_DATE, 'AD_ASST', 4000); END; / 1 - 49 Copyright © 2009, Oracle. All rights reserved. Updating Data: Example Increase the salary of all employees who are stock clerks. DECLARE sal_increase employees.salary%TYPE := 800; BEGIN UPDATE employees SET salary = salary + sal_increase WHERE job_id = 'ST_CLERK'; END; / ... 1 - 50 Copyright © 2009, Oracle. All rights reserved. Deleting Data: Example Delete rows that belong to department 10 from the employees table. DECLARE deptno employees.department_id%TYPE := 10; BEGIN DELETE FROM employees WHERE department_id = deptno; END; / 1 - 51 Copyright © 2009, Oracle. All rights reserved. Agenda • • • 1 - 52 Retrieving data with PL/SQL Manipulating data with PL/SQL Introducing SQL cursors Copyright © 2009, Oracle. All rights reserved. SQL Cursor • A cursor is a pointer to the private memory area allocated by the Oracle Server. It is used to handle the result set of a SELECT statement. • There are two types of cursors: implicit and explicit. – Implicit: Created and managed internally by the Oracle Server to process SQL statements – Explicit: Declared explicitly by the programmer Implicit cursor 1 - 53 Explicit cursor Copyright © 2009, Oracle. All rights reserved. SQL Cursor Attributes for Implicit Cursors Using SQL cursor attributes, you can test the outcome of your SQL statements. 1 - 54 SQL%FOUND Boolean attribute that evaluates to TRUE if the most recent SQL statement affected at least one row SQL%NOTFOUND Boolean attribute that evaluates to TRUE if the most recent SQL statement did not affect even one row SQL%ROWCOUNT An integer value that represents the number of rows affected by the most recent SQL statement Copyright © 2009, Oracle. All rights reserved. SQL Cursor Attributes for Implicit Cursors Delete rows that have the specified employee ID from the employees table. Print the number of rows deleted. Example: DECLARE v_rows_deleted VARCHAR2(30) v_empno employees.employee_id%TYPE := 176; BEGIN DELETE FROM employees WHERE employee_id = v_empno; v_rows_deleted := (SQL%ROWCOUNT || ' row deleted.'); DBMS_OUTPUT.PUT_LINE (v_rows_deleted); END; 1 - 55 Copyright © 2009, Oracle. All rights reserved. SQL%FOUND TRUE SQL%NOTFOUND FALSE SQL%ROWCOUNT 5 DECLARE v_deptno number :=80; BEGIN -- from GUI accept department id and delete all employees in that departments -- but if number of records being deleted greater than 10 employees cancel the job Copyright © 2009, Oracle. All rights reserved. DELETE employees 1 - 56