Download presentation
Presentation is loading. Please wait.
Published byNora Rice Modified over 8 years ago
1
Sheffield Hallam University – November 2006 Advanced Databases PL/SQL 1 Blocks, Variables & Control Structures Lynne Dawson November 2006
2
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
3
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
4
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
5
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
6
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
7
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
8
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
9
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 */
10
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
11
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, type @file.sql (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>
12
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 http://ivy.shu.ac.uk:5560/isqlplushttp://ivy.shu.ac.uk:5560/isqlplus Login
13
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
14
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
15
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
16
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
17
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
18
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
19
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
20
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
21
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
22
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**
23
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
24
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; /
25
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', '', '02-10-06', 'IT_MAN', 10000, '', 100, 60); END; /
26
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; /
27
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; /
28
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 + 2000; COMMIT; END; / BEGIN UPDATE employees SET salary = salary + 2000; END; / COMMIT;
29
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
30
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
31
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
32
Sheffield Hallam University – November 2006 Advanced Databases IF Statements Execution Flow IF condition THEN actions (including further IFs) Continue TRUEFALSE
33
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
34
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
35
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;
36
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'
37
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
38
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
39
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.
40
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
41
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; /
42
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
43
Sheffield Hallam University – November 2006 Advanced Databases Resources Books ORACLE 9i PL/SQL Programming Scott Urman, 2002 McGraw Hill/Osbourne, ISBN 0-07-219147-3 ORACLE PL/SQL Programming, 3 rd Edition Steve Feuerstein, 2002 O'Reilly, ISBN 0-596-00381-1 Additional Help Oracle Online Documentation http://oracledocs.shu.ac.uk/ Tutorial Workbooks
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.