1 Writing Control Structures Part D. 2 PL/SQL Decision Control Structures Sequential processing Sequential processing Processes statements one after another.

Slides:



Advertisements
Similar presentations
BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures.
Advertisements

AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
PL/SQL. Introduction to PL/SQL PL/SQL is the procedure extension to Oracle SQL. It is used to access an Oracle database from various environments (e.g.
PL/SQL.
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
MUCH ADO ABOUT NOTHING Walter Schenk SoluTech Consulting Services Inc.
PL/SQL (Procedural Language extensions to SQL) Prepared by: Manoj Kathpalia Edited by: M V Ramakrishna.
Chapter 4B: More Advanced PL/SQL Programming
PL/SQLPL/SQL Declaring Variables Declaring Variables Declaring Variables Declaring Variables Writing Executable Statements Writing Executable Statements.
Introduction to PL/SQL
1 PL/SQL programming Procedures and Cursors Lecture 1 Akhtar Ali.
Introduction to PL/SQL. Procedural Language extension for SQL Oracle Proprietary 3GL Capabilities Integration of SQL Portable within Oracle data bases.
1 Introduction to PL/SQL. 2  Procedural programming language  Uses detailed instructions  Processes statements sequentially  Combines SQL commands.
PL/SQL Anonymous Blocks
Lecture 4 Introduction to PL/SQL Procedures & Cursors.
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.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI
INTRODUCTION TO PL/SQL. Class Agenda Introduction Introduction to PL/SQL Declaring PL/SQL Variable Creating the Executable Section Interacting with the.
Chapter 4: Introduction to PL/SQL
About PL/SQL –PL/SQL is an extension to SQL with design features of programming languages. –Data manipulation and query statements of SQL are included.
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.
PL/SQL A BRIEF OVERVIEW DAVID WILSON. PL/SQL User’s Guide and Reference PL/SQL User’s Guide and Reference.
1. 1. Which type of argument passes a value from a procedure to the calling program? A. VARCHAR2 B. BOOLEAN C. OUT D. IN 2.
PL SQL Block Structures. What is PL SQL A good way to get acquainted with PL/SQL is to look at a sample program. PL/SQL combines the data manipulating.
Program with PL/SQL Lesson 4. Writing Control Structure.
1 CursorsCursors. 2 SQL Cursor A cursor is a private SQL work area. A cursor is a private SQL work area. There are two types of cursors: There are two.
PL/SQL Block Structure DECLARE - Optional Variables, cursors, user-defined exceptions BEGIN - Mandatory SQL Statements PL/SQL Statements EXCEPTIONS - Optional.
PL/SQL. Introduction to PL/SQL block Declare declarations Begin executable statement Exception exception handlers End;
Introduction to PL-SQL Introduction to PL-SQL Aj. ประวัฒน์ เปรมธีรสมบูรณ์ Lecture by.
Guide to Oracle 10g ITBIS373 Database Development Lecture 4a - Chapter 4: Using SQL Queries to Insert, Update, Delete, and View Data.
© ABB University - 1 Revision C E x t e n d e d A u t o m a t i o n S y s t e m x A Chapter 11 Structured Text Course T314.
Bordoloi and Bock Control Structures: Iterative Control.
Copyright  Oracle Corporation, All rights reserved. 18 Interacting with the Oracle Server.
implicit and an explicit cursor
1 PL/SQL Part C Scope and Interacting with the Oracle Server.
Program with PL/SQL Lesson 3. Interacting with the Oracle Server.
Copyright  Oracle Corporation, All rights reserved. 20 Working with Composite Datatypes.
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.
Database An introduction to using Oracle PL/SQL An introduction to using Oracle PL/SQL An introduction to using Oracle PL/SQL Definition: PL/SQL.
Sheffield Hallam University – November 2006 Advanced Databases PL/SQL 1 Blocks, Variables & Control Structures Lynne Dawson November 2006.
CS422 Principles of Database Systems Oracle PL/SQL Chengyu Sun California State University, Los Angeles.
CS422 Principles of Database Systems Stored Procedures and Triggers Chengyu Sun California State University, Los Angeles.
Program with PL/SQL Lesson 4.
Interacting with the Oracle8 Server
Interacting with the Oracle Server
Writing Control Structures
Interacting with the Oracle Server
Writing Executable Statements
Oracle11g: PL/SQL Programming Chapter 2 Basic PL/SQL Block Structures.
Oracle9i Developer: PL/SQL Programming Chapter 3 PL/SQL Processing.
Writing Control Structures
Database Management Systems 2
Interacting with the Oracle Server
جمل التحكم المحاضرة التاسعة T.Eman Alsqour.
جمل التحكم.
Working with Composite Datatypes
Introduction to PL/SQL Procedures & Cursors
Chapter 4: Introduction to PL/SQL
Chapter 2 Handling Data in PL/SQL Blocks Oracle9i Developer:
CS4222 Principles of Database System
Writing Control Structures
PL/SQL week10.
PL/SQL Declaring Variables.
Database Programming Using Oracle 11g
Database Programming Using Oracle 11g
Presentation transcript:

1 Writing Control Structures Part D

2 PL/SQL Decision Control Structures Sequential processing Sequential processing Processes statements one after another Processes statements one after another Decision control structures Decision control structures Alter order in which statements execute Alter order in which statements execute Based on values of certain variables Based on values of certain variables

3 Controlling PL/SQL Flow of Execution You can change the logical flow of statements using conditional IF statements and loop control structures. You can change the logical flow of statements using conditional IF statements and loop control structures. Conditional IF statements: Conditional IF statements: IF-THEN-END IF IF-THEN-END IF IF-THEN-ELSE-END IF IF-THEN-ELSE-END IF IF-THEN-ELSIF-END IF IF-THEN-ELSIF-END IF You can change the logical flow of statements using conditional IF statements and loop control structures. You can change the logical flow of statements using conditional IF statements and loop control structures. Conditional IF statements: Conditional IF statements: IF-THEN-END IF IF-THEN-END IF IF-THEN-ELSE-END IF IF-THEN-ELSE-END IF IF-THEN-ELSIF-END IF IF-THEN-ELSIF-END IF

4 IF Statements IF condition THEN statements; [ELSIF condition THEN statements;] [ELSE statements;] END IF; IF condition THEN statements; [ELSIF condition THEN statements;] [ELSE statements;] END IF; Syntax Simple IF statement: Set the manager ID to 22 if the employee name is Osborne. Syntax Simple IF statement: Set the manager ID to 22 if the employee name is Osborne. IF v_ename = 'OSBORNE' THEN v_mgr := 22; END IF; IF v_ename = 'OSBORNE' THEN v_mgr := 22; END IF;

5 PL/SQL Comparison Operators

6 Simple IF Statements Set the job title to Salesman, the department number to 35, and the commission to 20% of the current salary if the last name is Miller. Set the job title to Salesman, the department number to 35, and the commission to 20% of the current salary if the last name is Miller. Example Example Set the job title to Salesman, the department number to 35, and the commission to 20% of the current salary if the last name is Miller. Set the job title to Salesman, the department number to 35, and the commission to 20% of the current salary if the last name is Miller. Example Example... IF v_ename = 'MILLER' THEN v_job := 'SALESMAN'; v_deptno := 35; v_new_comm := sal * 0.20; END IF;... IF v_ename = 'MILLER' THEN v_job := 'SALESMAN'; v_deptno := 35; v_new_comm := sal * 0.20; END IF;...

7 IF-THEN-ELSE Statement Execution Flow IF condition TRUE THEN actions (including further IFs) THEN actions (including further IFs) FALSE ELSE actions (including further IFs) ELSE actions (including further IFs)

8 IF-THEN-ELSE Statements Set a flag for orders where there are fewer than five days between order date and ship date. Set a flag for orders where there are fewer than five days between order date and ship date. Example Example Set a flag for orders where there are fewer than five days between order date and ship date. Set a flag for orders where there are fewer than five days between order date and ship date. Example Example... IF v_shipdate - v_orderdate < 5 THEN v_ship_flag := 'Acceptable'; ELSE v_ship_flag := 'Unacceptable'; END IF;... IF v_shipdate - v_orderdate < 5 THEN v_ship_flag := 'Acceptable'; ELSE v_ship_flag := 'Unacceptable'; END IF;...

9 IF-THEN-ELSIF Statement Execution Flow IF condition TRUE THEN actions FALSE ELSIFconditionELSIFcondition TRUE FALSE ELSEactionsELSEactions

10 IF-THEN-ELSIF Statements For a given value, calculate a percentage of that value based on a condition. For a given value, calculate a percentage of that value based on a condition. Example Example For a given value, calculate a percentage of that value based on a condition. For a given value, calculate a percentage of that value based on a condition. Example Example... IF v_start > 100 THEN v_start := 2 * v_start; ELSIF v_start >= 50 THEN v_start :=.5 * v_start; ELSE v_start :=.1 * v_start; END IF;... IF v_start > 100 THEN v_start := 2 * v_start; ELSIF v_start >= 50 THEN v_start :=.5 * v_start; ELSE v_start :=.1 * v_start; END IF;...

11 Building Logical Conditions You can handle null values with the IS NULL operator. You can handle null values with the IS NULL operator. Any arithmetic expression containing a null value evaluates to NULL. Any arithmetic expression containing a null value evaluates to NULL. Concatenated expressions with null values treat null values as an empty string. Concatenated expressions with null values treat null values as an empty string. NULL acts as False NULL acts as False The IS NULL condition evaluates to TRUE only if the variable it is checking is NULL. The IS NULL condition evaluates to TRUE only if the variable it is checking is NULL. You can handle null values with the IS NULL operator. You can handle null values with the IS NULL operator. Any arithmetic expression containing a null value evaluates to NULL. Any arithmetic expression containing a null value evaluates to NULL. Concatenated expressions with null values treat null values as an empty string. Concatenated expressions with null values treat null values as an empty string. NULL acts as False NULL acts as False The IS NULL condition evaluates to TRUE only if the variable it is checking is NULL. The IS NULL condition evaluates to TRUE only if the variable it is checking is NULL.

12 Logic Tables Build a simple Boolean condition with a comparison operator. Build a simple Boolean condition with a comparison operator. NOT TRUE FALSE NULL OR TRUE FALSE NULL TRUEFALSENULL FALSE TRUE NULL AND TRUE FALSE NULL TRUEFALSENULL TRUE NULL FALSE TRUE FALSE NULL

13 Boolean Conditions What is the value of V_FLAG in each case? What is the value of V_FLAG in each case? V_REORDER_FLAGV_AVAILABLE_FLAGV_FLAG TRUE TRUEFALSE NULLTRUE NULLFALSE v_flag := v_reorder_flag AND v_available_flag; TRUEFALSENULLFALSE

14 Evaluating AND and OR in an Expression

15 Loops Systematically executes program statements Systematically executes program statements Periodically evaluates exit condition to determine if loop should repeat or exit Periodically evaluates exit condition to determine if loop should repeat or exit Pretest loop Pretest loop Evaluates exit condition before any program commands execute Evaluates exit condition before any program commands execute Posttest loop Posttest loop Executes program commands before loop evaluates exit condition for first time Executes program commands before loop evaluates exit condition for first time

16 Iterative Control: LOOP Statements Loops repeat a statement or sequence of statements multiple times. Loops repeat a statement or sequence of statements multiple times. There are three loop types: There are three loop types: Basic loop Basic loop FOR loop FOR loop WHILE loop WHILE loop Loops repeat a statement or sequence of statements multiple times. Loops repeat a statement or sequence of statements multiple times. There are three loop types: There are three loop types: Basic loop Basic loop FOR loop FOR loop WHILE loop WHILE loop

17 Basic Loop Syntax Syntax LOOP statement1;... EXIT [WHEN condition]; END LOOP; LOOP statement1;... EXIT [WHEN condition]; END LOOP; where:conditionis a Boolean variable or expression (TRUE, FALSE, or NULL); where:conditionis a Boolean variable or expression (TRUE, FALSE, or NULL); -- delimiter -- statements -- EXIT statement -- delimiter A basic loop can contain multiple EXIT statements.

18 Basic Loop DECLARE v_ordiditem.ordid%TYPE := 601; v_counterNUMBER(2) := 1; BEGIN LOOP INSERT INTO item(ordid, itemid) VALUES(v_ordid, v_counter); v_counter := v_counter + 1; EXIT WHEN v_counter > 10; END LOOP; END; DECLARE v_ordiditem.ordid%TYPE := 601; v_counterNUMBER(2) := 1; BEGIN LOOP INSERT INTO item(ordid, itemid) VALUES(v_ordid, v_counter); v_counter := v_counter + 1; EXIT WHEN v_counter > 10; END LOOP; END; Example Example

19 FOR Loop Syntax Syntax Use a FOR loop to shortcut the test for the number of iterations. Use a FOR loop to shortcut the test for the number of iterations. Do not declare the counter; it is declared implicitly. Do not declare the counter; it is declared implicitly. The lower bound and upper bound of the loop range can be literals, variables, or expressions, but must evaluate to integers The lower bound and upper bound of the loop range can be literals, variables, or expressions, but must evaluate to integers Syntax Syntax Use a FOR loop to shortcut the test for the number of iterations. Use a FOR loop to shortcut the test for the number of iterations. Do not declare the counter; it is declared implicitly. Do not declare the counter; it is declared implicitly. The lower bound and upper bound of the loop range can be literals, variables, or expressions, but must evaluate to integers The lower bound and upper bound of the loop range can be literals, variables, or expressions, but must evaluate to integers FOR counter in [REVERSE] lower_bound..upper_bound LOOP statement1; statement2;... END LOOP; FOR counter in [REVERSE] lower_bound..upper_bound LOOP statement1; statement2;... END LOOP;

20 FOR Loop Guidelines Guidelines Reference the counter within the loop only; it is undefined outside the loop. Reference the counter within the loop only; it is undefined outside the loop. The lower and upper bounds of the loop could be values, variables, or expressions The lower and upper bounds of the loop could be values, variables, or expressions Do not reference the counter as the target of an assignment. An error message rises if you do so. Do not reference the counter as the target of an assignment. An error message rises if you do so. Guidelines Guidelines Reference the counter within the loop only; it is undefined outside the loop. Reference the counter within the loop only; it is undefined outside the loop. The lower and upper bounds of the loop could be values, variables, or expressions The lower and upper bounds of the loop could be values, variables, or expressions Do not reference the counter as the target of an assignment. An error message rises if you do so. Do not reference the counter as the target of an assignment. An error message rises if you do so.

21 FOR Loop Insert the first 10 new line items for order number 601. Insert the first 10 new line items for order number 601. Example Example Insert the first 10 new line items for order number 601. Insert the first 10 new line items for order number 601. Example Example DECLARE v_ordiditem.ordid%TYPE := 601; BEGIN FOR i IN LOOP INSERT INTO item(ordid, itemid) VALUES(v_ordid, i); END LOOP; END; DECLARE v_ordiditem.ordid%TYPE := 601; BEGIN FOR i IN LOOP INSERT INTO item(ordid, itemid) VALUES(v_ordid, i); END LOOP; END;

22 WHILE Loop Syntax Syntax Use the WHILE loop to repeat statements while a condition is TRUE. Use the WHILE loop to repeat statements while a condition is TRUE. Syntax Syntax Use the WHILE loop to repeat statements while a condition is TRUE. Use the WHILE loop to repeat statements while a condition is TRUE. WHILE condition LOOP statement1; statement2;... END LOOP; WHILE condition LOOP statement1; statement2;... END LOOP; Condition is evaluated at the beginning of each iteration.

23 WHILE Loop Example Example SQL>ACCEPT v_dept_name PROMPT 'Enter the dept. name: ' SQL>ACCEPT num_depts PROMPT 'Enter number of depts: ' SQL>DECLARE v_countNUMBER(2) := 1; BEGIN WHILE v_count <= &num_depts LOOP INSERT INTO dept(deptno,dname) VALUES ( v_count, &v_dept_name ); v_count := v_count + 1; END LOOP; COMMIT; END; / SQL>ACCEPT v_dept_name PROMPT 'Enter the dept. name: ' SQL>ACCEPT num_depts PROMPT 'Enter number of depts: ' SQL>DECLARE v_countNUMBER(2) := 1; BEGIN WHILE v_count <= &num_depts LOOP INSERT INTO dept(deptno,dname) VALUES ( v_count, &v_dept_name ); v_count := v_count + 1; END LOOP; COMMIT; END; /

24 Working with Composite Datatypes

25 The %ROWTYPE Attribute Declare a variable according to a collection of columns in a database table or view. Declare a variable according to a collection of columns in a database table or view. Prefix %ROWTYPE with the database table. Prefix %ROWTYPE with the database table. Fields in the record take their names and datatypes from the columns of the table or view. Fields in the record take their names and datatypes from the columns of the table or view. Declare a variable according to a collection of columns in a database table or view. Declare a variable according to a collection of columns in a database table or view. Prefix %ROWTYPE with the database table. Prefix %ROWTYPE with the database table. Fields in the record take their names and datatypes from the columns of the table or view. Fields in the record take their names and datatypes from the columns of the table or view.

26 The %ROWTYPE Attribute Examples Examples Declare a variable to store the same information about a department as it is stored in the DEPT table. Declare a variable to store the same information about a department as it is stored in the DEPT table. Declare a variable to store the same information about an employee as it is stored in the EMP table. Declare a variable to store the same information about an employee as it is stored in the EMP table. Examples Examples Declare a variable to store the same information about a department as it is stored in the DEPT table. Declare a variable to store the same information about a department as it is stored in the DEPT table. Declare a variable to store the same information about an employee as it is stored in the EMP table. Declare a variable to store the same information about an employee as it is stored in the EMP table. dept_recorddept%ROWTYPE; emp_recordemp%ROWTYPE;

27 %ROWTYPE Example SQL> SET SERVEROUTPUT ON; SQL> DECLARE d dept%ROWTYPE; d dept%ROWTYPE; BEGIN BEGIN SELECT deptno,dname,loc INTO d FROM dept WHERE deptno=10; SELECT deptno,dname,loc INTO d FROM dept WHERE deptno=10; DBMS_OUTPUT.PUT_LINE(d.dname); DBMS_OUTPUT.PUT_LINE(d.dname); END; END; /ACCOUNTING