Sheffield Hallam University – November 2006 Advanced Databases PL/SQL 1 Blocks, Variables & Control Structures Lynne Dawson November 2006.

Slides:



Advertisements
Similar presentations
AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
Advertisements

PL/SQL.
PL/SQL (Procedural Language extensions to SQL) Prepared by: Manoj Kathpalia Edited by: M V Ramakrishna.
Lecture-5 Though SQL is the natural language of the DBA, it suffers from various inherent disadvantages, when used as a conventional programming language.
Chapter 4B: More Advanced PL/SQL Programming
Advanced Package Concepts. 2 home back first prev next last What Will I Learn? Write packages that use the overloading feature Write packages that use.
Introduction to PL/SQL
Dr. James Dullea, CSC8490 Introduction to PL/SQLSlide 1 of 36 7From Prof. Dullea CSC8490 Introduction to PL/SQL Module 01-9 Revised: June 12, 2005 Dr.
Bordoloi and Bock CURSORS. Bordoloi and Bock CURSOR MANIPULATION To process an SQL statement, ORACLE needs to create an area of memory known as the context.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
1 Introduction to PL/SQL. 2  Procedural programming language  Uses detailed instructions  Processes statements sequentially  Combines SQL commands.
SQL enables us to create, organize, retrieve and maintain data stored in database it does not provide the features which a typical programming language.
EE Copyright س Oracle Corporation, All rights reserved. ® Review of PL/SQL.
Lecture 4 PL/SQL language. PL/SQL – procedural SQL Allows combining procedural and SQL code PL/SQL code is compiled, including SQL commands PL/SQL code.
Oracle10g Developer: PL/SQL Programming1 Objectives Programming fundamentals The PL/SQL block Define and declare variables Initialize variables The NOT.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 2 Basic PL/SQL Block Structures.
PL/SQL Loops. Building Logical Conditions All logical conditions must yield a boolean condition. You can build a simple Boolean condition by combining.
Interacting With The Oracle Server. Objectives After completing this lesson, you should be able to do the following: Write a successful SELECT statement.
L/O/G/O Introduction to PL/SQL Oracle Database 10g Develop PLSQL Program Units.
INTRODUCTION TO PL/SQL. Class Agenda Introduction Introduction to PL/SQL Declaring PL/SQL Variable Creating the Executable Section Interacting with the.
1 Copyright © 2004, Oracle. All rights reserved. Introduction to PL/SQL.
PL/SQL : INTRODUCTION. PL/SQL PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database language. With PL/SQL, you.
Program with PL/SQL Lesson 5. Working with Composite Data Types.
Program with PL/SQL. Interacting with the Oracle Server.
Overview · What is PL/SQL · Advantages of PL/SQL · Basic Structure of a PL/SQL Block · Procedure · Function · Anonymous Block · Types of Block · Declaring.
Objectives After completing this lesson, you should be able to do the following: Describe each data manipulation language (DML) statement Insert rows.
Program with PL/SQL Lesson 4. Writing Control Structure.
CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Stored Procedure James Wang.
PL / SQL By Mohammed Baihan. What is PL/SQL? PL/SQL stands for Procedural Language extension of SQL. PL/SQL is a combination of SQL along with the procedural.
1 Copyright © 2004, Oracle. All rights reserved. Introduction to PL/SQL.
CIS4368: Advanced DatabaseSlide # 1 PL/SQL Dr. Peeter KirsSpring, 2003 PL/SQL.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
PL/SQL Block Structure DECLARE - Optional Variables, cursors, user-defined exceptions BEGIN - Mandatory SQL Statements PL/SQL Statements EXCEPTIONS - Optional.
PL/SQL Declaring Variables PL/SQL Block Structure DECLARE (Optional) Variables, cursors, user-defined exceptions BEGIN (Mandatory) - SQL statements -
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
Database Application Development using PL/SQL Programming.
Guide to Oracle 10g ITBIS373 Database Development Lecture 4a - Chapter 4: Using SQL Queries to Insert, Update, Delete, and View Data.
Introduction to PL/SQL. Objectives  After completing this lesson, you should be able to do the following:  Explain the need for PL/SQL  Explain the.
1 PL/SQLPL/SQL Declaring Variables Declaring Variables Declaring Variables Declaring Variables Writing Executable Statements Writing Executable Statements.
Copyright  Oracle Corporation, All rights reserved. 16 Declaring Variables.
1 Writing Control Structures Part D. 2 PL/SQL Decision Control Structures Sequential processing Sequential processing Processes statements one after another.
Retrieving Data in PL/SQL. 2 home back first prev next last What Will I Learn? In this lesson, you will learn to: –Recognize the SQL statements that can.
implicit and an explicit cursor
Declaring PL/SQL Variables
1 PL/SQL Part C Scope and Interacting with the Oracle Server.
Oracle10g Developer: PL/SQL Programming1 Objectives Named program units How to identify parameters The CREATE PROCEDURE statement Creating a procedure.
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
Introduction to PL/SQL Francis Thottungal. The outline The basic PL/SQL code structure is : DECLARE -- optional, which declares and define variables,
Program with PL/SQL Lesson 3. Interacting with the Oracle Server.
Lab 2 Writing PL/SQL Blocks CISB514 Advanced Database Systems.
Kingdom of Saudi Arabia Ministry of Higher Education Al-Imam Muhammad Ibn Saud Islamic University College of Computer and Information Sciences Overview.
PL/SQL Writing Executable Statements. PL/SQL Block Syntax and Guidelines Statement can be split across lines, but keywords must not be split Lexical units.
Introduction to PL/SQL N. Dimililer. About PL/SQL –PL/SQL is an extension to SQL with design features of programming languages. –Data manipulation and.
CS422 Principles of Database Systems Oracle PL/SQL Chengyu Sun California State University, Los Angeles.
1 Copyright © 2004, Oracle. All rights reserved. PL/SQL Programming Concepts: Review.
3 Copyright © 2004, Oracle. All rights reserved. Writing Executable Statements.
PLSQL Cont…. Most Common Oracle Data Types VARCHAR2 –Stores variable-length character data. –Takes a required parameter that specifies a maximum length.
CS322: Database Systems PL/ SQL PL/SQL by Ivan Bayross.
Program with PL/SQL Lesson 4.
Interacting with the Oracle Server
Interacting with the Oracle Server
Oracle11g: PL/SQL Programming Chapter 2 Basic PL/SQL Block Structures.
Database Management Systems 2
PL/SQL Scripting in Oracle:
Sa0951a PL/SQL 1: Introduction
Chapter 4: Introduction to PL/SQL
Writing Control Structures
Contents Preface I Introduction Lesson Objectives I-2
Chapter 8 Advanced SQL.
PL/SQL Declaring Variables.
Presentation transcript:

Sheffield Hallam University – November 2006 Advanced Databases PL/SQL 1 Blocks, Variables & Control Structures Lynne Dawson November 2006

Sheffield Hallam University – November 2006 Advanced Databases Tutorials 3 weeks of PL/SQL Lectures 3 Workbooks Pre-Requisites  Examples – understand what they are doing  Exercises – work through them  Answers  SQL knowledge  SQL*Plus knowledge

Sheffield Hallam University – November 2006 Advanced Databases Aims Understand what PL/SQL is Recognise the basic PL/SQL block and its sections Declare PL/SQL variables and assign values Execute a PL/SQL block Understand nested blocks and variable scope Write maintainable PL/SQL code Write SELECT and DML statements in PL/SQL Construct IF statements Construct Basic, FOR and WHILE loops Understand nested loops

Sheffield Hallam University – November 2006 Advanced Databases SQL About PL/SQL PL/SQL is an extension to SQL You can incorporate SQL DML commands, but not DDL It has programming design features SQL*Plus PL/SQL

Sheffield Hallam University – November 2006 Advanced Databases Advantages of PL/SQL Programmer retains control Integration PL/SQL SQL-1 PL/SQL SQL-2 SQL-3 PL/SQL SQL-4 PL/SQL SQL-1 SQL-2 SQL-3 SQL-4 PL/SQL SQL-1SQL-3 SQL-2SQL-4 Improved performance – one package rather than lots of individual SQL calls CODEPL/SQL ENGINE SQL EXECUTOR  can have sub-programs which can be referenced and re-used  can ensure same datatypes as used throughout

Sheffield Hallam University – November 2006 Advanced Databases PL/SQL Block Structure BEGIN (mandatory) /* Executable Section e.g. SQL statements, PL/SQL Statements */ DECLARE (optional) /* Declarative Section e.g. variables, constants, cursors*/ EXCEPTION (optional) /* Actions to perform when error occur executable section */ END; (mandatory) / Block Structured language Logical Block - Basic units (procedures, functions, anonymous blocks) which make up a program A PL/SQL block is terminated by a slash (/) on a line by itself Statements can continue over several lines

Sheffield Hallam University – November 2006 Advanced Databases Types of Blocks Anonymous Blocks Stored Procedures / Functions Packages Triggers  Unnamed – cannot be referenced  Compiled at every run time  Can be re-used by any application using the database  Can pass parameters into and out of them  Group of related procedures / functions, e.g. DBMS_OUTPUT  Executed implicitly when a event happens

Sheffield Hallam University – November 2006 Advanced Databases SELECT Statements in PL/SQL Use a SELECT statement (in the BEGIN section) to retrieve data from database Syntax BEGIN SELECTselect_list INTO{variable_name[, variable_name]....} FROMtable WHEREcondition; END; / INTO clause WHERE clause must ensure only ONE row is returned  Mandatory  Occurs between SELECT and FROM  Number of variables listed must match number of columns selected  Variable order matches column order

Sheffield Hallam University – November 2006 Advanced Databases PL/SQL Block Syntax Literals v_lastname := 'Henderson';  Numbers can be simple values or scientific notation Comments DECLARE -- Define the local variable for salary v_salaryNUMBER(9,2); BEGIN /* Compute the annual salary based on the monthly salary input from the user */ v_salary:= &p_monthly_salary * 12; END; /  Character and data literals must be enclosed in single quotation marks  Prefix single-line comments with two dashes (--)  Put multi-line comments between the symbols /* and */

Sheffield Hallam University – November 2006 Advanced Databases PL/SQL Programming Guidelines Make code maintenance easier by: Documenting code with comments Single line (--....) Multi-line (/*....*/) Developing a case convention for the code, e.g. Upper case for reserved words e.g. SELECT, FROM Lower case for tables, columns, variables e.g. lastname employee_id v_employee_id Enhance readability by indenting code, e.g. indent each level of code

Sheffield Hallam University – November 2006 Advanced Databases PL/SQL Execution To execute PL/SQL Write code in Notepad/Textpad Save as file.sql in your F:\MyWork\Oracle directory (this is where Oracle looks for files by default) At SQL> prompt, (If file not saved in F:\MyWork\Oracle you will need to type in the full path name) To start SQL*Plus All Programs -> Specialist Applications -> Oracle -> Oracle SQL*Plus for Windows Login Get a prompt SQL>

Sheffield Hallam University – November 2006 Advanced Databases PL/SQL Execution To execute PL/SQL Write code in Workspace area Click Execute button (results appear below) To save code to a file (for future use) click the "Save Script" button. Code can be reused by clicking the "Load Script" button and selecting the relevant file To start iSQL*Plus Start Internet Explorer Go to Login

Sheffield Hallam University – November 2006 Advanced Databases Variables Use variables for:  Temporary storage of data  Manipulation of stored values  Reusability  Ease of maintenance Declare and initialise variables in declaration section Assign values to variables in executable section View results through bind variables in SQL*Plus Values of variables can be altered by using PL/SQL DECLARE v_dept_name VARCHAR2(30) := 'Finance'; BEGIN v_counter := v_counter + 1; PRINT g_dept_name

Sheffield Hallam University – November 2006 Advanced Databases Types of Variables PL/SQL variables CHAR VARCHAR2 NUMBER  Scalar −VARCHAR2 (maximum_length) −CHAR [(maximum_length)] −NUMBER [(precision, scale)] −BOOLEAN −DATE −TIMESTAMP  Composite −RECORDS −TABLES −VARRAYS  Reference −Cursors  LOB (large objects) Non-PL/SQL variables:  Bind variables RECORDS VARRAYS CURSORS BIND

Sheffield Hallam University – November 2006 Advanced Databases Declaring PL/SQL Variables Syntax identifier [CONSTANT] datatype [NOT NULL] [:= DEFAULT|expr]; Example DECLARE v_hiredate DATE; v_dept_name VARCHAR2(30) NOT NULL := 'Finance; v_location_id NUMBER(4) := '1700'; c_commisson_pct CONSTANT NUMBER (2,2) := 0.25; Initialise variables designated as NOT NULL and CONSTANT Initialise identifiers by using the assignment operator (:=) Declare ONLY ONE identifier per line

Sheffield Hallam University – November 2006 Advanced Databases The %TYPE Attribute Declare a variable according to:... v_lastnameemployee.lastname%TYPE; v_balanceNUMBER(10,2); v_min_balancev_balance%TYPE := 10.32;... Example  A database column definition  Another previously declared variable Prefix %TYPE with:  The database table and column  The previously declared variable name

Sheffield Hallam University – November 2006 Advanced Databases Can contain up to 30 characters Naming PL/SQL Variables Two variables can have the same name, provided they are in different blocks Develop a naming convention for variables, e.g. v_xxxfor local (block) variables c_xxxfor constants g_xxxfor bind (global) variables Must begin with an alphabetic character Should not have the same name as a database table column name

Sheffield Hallam University – November 2006 Advanced Databases Naming Rules Use a naming convention to avoid ambiguity in the WHERE clause DECLARE employee_idNUMBER(6); last_nameVARCHAR2(25):= 'Smith'; BEGIN SELECTemployee_id(column name) INTOemployee_id(variable name) FROMemployees WHERElast_name = last_name; END; / Syntax errors can arise because PL/SQL checks the database first for a column in the table. No confusion in the SELECT clause as all identifiers are deemed to be column names No confusion in the INTO clause as all identifiers are deemed to be variables

Sheffield Hallam University – November 2006 Advanced Databases SQL*PLUS PL/SQL Bind Variables SQL employee_id SQL SELECT employee_id FROM employees WHERE last_name = 'Smith'; PL/SQL SELECT employee_id INTO v_emp_id FROM employees WHERE last_name = 'Smith'; SQL*PLUS VARIABLE g_id NUMBER DECLARE v_emp_id NUMBER BEGIN --PL/SQL block goes here :g_id := v_emp_id; END; / PRINT g_id v_emp_id g_id

Sheffield Hallam University – November 2006 Advanced Databases DBMS_OUTPUT.PUT_LINE An Oracle-supplied packaged procedure SET SERVEROUTPUT ON DECLARE v_employee_idNUMBER(6); BEGIN SELECT employee_id INTO v_emp_id FROM employees WHERE last_name = 'Smith'; DBMS_OUTPUT.PUT_LINE ('The employee id is ' || TO_CHAR(v_emp_id) ); END; / An alternative for displaying data from a PL/SQL block Must be enabled in SQL*Plus with SET SERVEROUTPUT ON

Sheffield Hallam University – November 2006 Advanced Databases SQL Statements in PL/SQL Extract a row of data from the database by using the SELECT command. Only a single set of values can be returned. Control a transaction with the commands  COMMIT  ROLLBACK  SAVEPOINT Make changes to rows in the database by using DML commands  INSERT  UPDATE  DELETE

Sheffield Hallam University – November 2006 Advanced Databases Operators in PL/SQL Logical AND, OR, NOT Arithmetic +, -, *, / Concatenation || Parenthesis to control( ) order of operations Comparison=, !=,, = ISNULL, LIKE, BETWEEN, IN Exponential operator**

Sheffield Hallam University – November 2006 Advanced Databases SELECT MAX(salary)v_max_salary := MAX(salary) INTO v_max_salary FROM jobs; SQL Functions in PL/SQL Available in PL/SQL statements:  Single-row functions which operate on one value and return one value −number (e.g. LENGTH, SUBSTR, LOG, ROUND ) −character (e.g. UPPER, LOWER )  Date/Timestamp functions (e.g. ADD_MONTHS, SYSDATE )  Datatype conversion (e.g. TO_CHAR, TO_NUMBER, TO_DATE ) Not available in PL/SQL statements:  Group functions (e.g. SUM, MAX, MIN, COUNT, AVG )   But CAN use them in SQL SELECT statements

Sheffield Hallam University – November 2006 Advanced Databases Retrieving Data in PL/SQL Example Retrieve the location and department name for a given department identifier DECLARE v_location_idNUMBER(4); v_department_nameVARCHAR2(30); BEGIN SELECTlocation_id, department_name INTOv_location_id, v_department_name FROMdepartments WHEREdepartment_id = 100; END; /

Sheffield Hallam University – November 2006 Advanced Databases Inserting Data in PL/SQL Example Add a new employee to the EMPLOYEES table DECLARE v_deptnoNUMBER(2); v_locVARCHAR2(15); BEGIN INSERT INTOemployees VALUES(employees_seq.NEXTVAL, 'Fred', 'Bloggs', 'FBLOGGS', '', ' ', 'IT_MAN', 10000, '', 100, 60); END; /

Sheffield Hallam University – November 2006 Advanced Databases Updating Data in PL/SQL Example Increase the salary of all employees in the EMPLOYEES table who are Programmers. DECLARE v_sal_increaseemployees.salary%TYPE := 2000; BEGIN UPDATEemployees SETsalary = salary + v_sal_increase WHEREjob_id = 'IT_PROG'; END; /

Sheffield Hallam University – November 2006 Advanced Databases Deleting Data in PL/SQL Example Delete rows that belong to department 230 from the EMPLOYEES table DECLARE v_dept_idemployees.department_id%TYPE := 230; BEGIN DELETE FROMemployees WHEREdepartment_id = v_dept_id; END; /

Sheffield Hallam University – November 2006 Advanced Databases COMMIT and ROLLBACK Initiate a transaction with the first DML command (INSERT, UPDATE or DELETE) which follows a COMMIT or ROLLBACK Use COMMIT and ROLLBACK to terminate a transaction explicitly They may be used within a PL/SQL block or within the host environment, e.g. SQL*Plus BEGIN UPDATE employees SET salary = salary ; COMMIT; END; / BEGIN UPDATE employees SET salary = salary ; END; / COMMIT;

Sheffield Hallam University – November 2006 Advanced Databases Nested Blocks Statements can be nested wherever an executable statement is allowed DECLARE... BEGIN..... DECLARE... BEGIN... END;..... END; / A nested block becomes a statement The scope of an object is the region of the program that can refer to the object

Sheffield Hallam University – November 2006 Advanced Databases Variable Scope A variable is visible in the regions in which you can reference the unqualified variable: DECLARE xNUMBER; BEGIN x := y; DECLARE yNUMBER; BEGIN y := x + 1; END;..... END; / Scope of x Scope of y A block CAN look up to the enclosing block A block CANNOT look down to the enclosed blocks 

Sheffield Hallam University – November 2006 Advanced Databases Control Structures Conditional Control Iterative Control  changes the logical flow of statements  allows alternative actions to be specified using − IF-THEN − IF-THEN-ELSE − IF-THEN-ELSIF  loops enable multiple execution of a statement or sequence of statements  three types of loop − BASIC − FOR − WHILE

Sheffield Hallam University – November 2006 Advanced Databases IF Statements Execution Flow IF condition THEN actions (including further IFs) Continue TRUEFALSE

Sheffield Hallam University – November 2006 Advanced Databases IF-THEN-ELSE Statements Execution Flow IF condition THEN actions (including further IFs) ELSE actions (including further IFs) TRUEFALSE

Sheffield Hallam University – November 2006 Advanced Databases IF-THEN-ELSIF Statements Execution Flow IF condition THEN actions ELSE actions TRUEFALSE ELSIF condition THEN actions TRUEFALSE

Sheffield Hallam University – November 2006 Advanced Databases IF Statements Syntax IF condition THEN statements [ ELSIF condition THEN statements;] [ ELSE statements;] END IF; Example Set the variable for manager ID to 100 if the employee's last name is Bloggs IF v_last_name = 'Bloggs' THEN v_manager_id := 100; END IF;

Sheffield Hallam University – November 2006 Advanced Databases Building Logical Conditions Handle NULL values with the IS NULL operator The IS NULL condition evaluates to TRUE only if the variable it is checking is NULL Any arithmetic expression containing a NULL value evaluates to NULL Concatenated expressions with NULL values treat NULL values as an empty string e.g. 3 + NULL = NULL e.g. 'Cat' + NULL = 'Cat'

Sheffield Hallam University – November 2006 Advanced Databases Basic Loop Syntax LOOP statement1;... EXIT [WHEN condition]; END LOOP; where condition is a Boolean variable or expression Without the EXIT clause the loop would be infinite. The EXIT clause must be within the loop. The loop is executed AT LEAST once, even if the WHEN condition is met upon entering the loop If no WHEN condition, then loop will ONLY execute ONCE

Sheffield Hallam University – November 2006 Advanced Databases FOR Loop Syntax FOR counter IN [REVERSE] lower_boundary..upper_bound LOOP statement1; statement2;... END LOOP; Use a FOR loop to shortcut the test for the number of iterations Do NOT declare the counter; it is declared implicitly Reference the counter only within the FOR loop Will execute loop a set number of times

Sheffield Hallam University – November 2006 Advanced Databases WHILE Loop Syntax WHILE condition LOOP statement1; statement2;... END LOOP; Use the WHILE loop to repeat statements while a condition is TRUE May NOT execute loop at all, if condition is initially FALSE.

Sheffield Hallam University – November 2006 Advanced Databases Nested Loops and Labels Nest loops to multiple levels Nest different types of loops within each other Use labels to distinguish between blocks and loops Exit the outer loop with the EXIT statement referencing the label Label loops by placing the label before the keyword LOOP within the label delimiters ( >) If a loop is labelled, the label can be used with the END LOOP statement for clarity

Sheffield Hallam University – November 2006 Advanced Databases Nested Loops... BEGIN > LOOP v_counter := v_counter + 1; EXIT WHEN v_counter > 10; > LOOP... EXIT Outer Loop WHEN total_done = 'YES'; -- Leave both loops EXIT Inner Loop WHEN inner_done = 'YES'; -- Leave inner loop only... END LOOP Inner Loop;... END LOOP Outer Loop; END; /

Sheffield Hallam University – November 2006 Advanced Databases Summary Understand PL/SQL Block Structure Write and execute PL/SQL blocks Declare, name and assign values to PL/SQL variables Understand Bind variables Write executable PL/SQL statements using SQL operators and functions Change data using PL/SQL statements Nested blocks and variable scope Conditional Control Iterative Control Nested Loops

Sheffield Hallam University – November 2006 Advanced Databases Resources Books  ORACLE 9i PL/SQL Programming Scott Urman, 2002 McGraw Hill/Osbourne, ISBN  ORACLE PL/SQL Programming, 3 rd Edition Steve Feuerstein, 2002 O'Reilly, ISBN Additional Help  Oracle Online Documentation  Tutorial Workbooks