43
2 Copyright © 2006, Oracle. All rights reserved. Writing Executable Statements

02 Writing Executable Statments

Embed Size (px)

DESCRIPTION

Oracle 10g PL / SQL Slides Lecture 02.

Citation preview

Page 1: 02 Writing Executable Statments

2Copyright © 2006, Oracle. All rights reserved.

Writing Executable Statements

Page 2: 02 Writing Executable Statments

2-2 Copyright © 2006, 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:– Identifiers – Delimiters– Literals– Comments

Page 3: 02 Writing Executable Statments

2-3 Copyright © 2006, Oracle. All rights reserved.

PL/SQL Block Syntax and Guidelines

• Literals:– Character and date literals must be enclosed in

single quotation marks.

– Numbers can be simple values or scientific notation.

• Statements can continue over several lines.

name := 'Henderson';

Page 4: 02 Writing Executable Statments

2-4 Copyright © 2006, Oracle. All rights reserved.

Commenting Code

• Prefix single-line comments with two hyphens (--).

• Place multiple-line comments between the symbols /* and */.

Example

DECLARE...annual_sal NUMBER (9,2);BEGIN -- Begin the executable section /* Compute the annual salary based on the monthly salary input from the user */annual_sal := monthly_sal * 12;END; -- This is the end of the block/

Page 5: 02 Writing Executable Statments

2-5 Copyright © 2006, Oracle. All rights reserved.

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

Page 6: 02 Writing Executable Statments

2-6 Copyright © 2006, Oracle. All rights reserved.

Data Type Conversion

• 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

Page 7: 02 Writing Executable Statments

2-7 Copyright © 2006, Oracle. All rights reserved.

Nested Blocks

PL/SQL blocks can be nested.

• An executable section (BEGIN … END) can contain nested blocks.

• An exception section can contain nested blocks.

Page 8: 02 Writing Executable Statments

2-8 Copyright © 2006, Oracle. All rights reserved.

Nested Blocks

DECLARE outer_variable VARCHAR2(20):='GLOBAL VARIABLE';BEGIN DECLARE inner_variable VARCHAR2(20):='LOCAL VARIABLE'; BEGIN DBMS_OUTPUT.PUT_LINE(inner_variable); DBMS_OUTPUT.PUT_LINE(outer_variable); END; DBMS_OUTPUT.PUT_LINE(outer_variable); END;/

Example

Page 9: 02 Writing Executable Statments

2-9 Copyright © 2006, Oracle. All rights reserved.

Variable Scope and Visibility

DECLARE father_name VARCHAR2(20):='Patrick'; date_of_birth DATE:='20-Apr-1972';BEGIN DECLARE child_name VARCHAR2(20):='Mike'; date_of_birth DATE:='12-Dec-2002'; BEGIN DBMS_OUTPUT.PUT_LINE('Father''s Name: '||father_name); DBMS_OUTPUT.PUT_LINE('Date of Birth: '||date_of_birth); DBMS_OUTPUT.PUT_LINE('Child''s Name: '||child_name); END; DBMS_OUTPUT.PUT_LINE('Date of Birth: '||date_of_birth); END;/

1

2

Page 10: 02 Writing Executable Statments

2-10 Copyright © 2006, Oracle. All rights reserved.

Qualify an Identifier

<<outer>>DECLARE father_name VARCHAR2(20):='Patrick'; date_of_birth DATE:='20-Apr-1972';BEGIN DECLARE child_name VARCHAR2(20):='Mike'; date_of_birth DATE:='12-Dec-2002'; BEGIN DBMS_OUTPUT.PUT_LINE('Father''s Name: '||father_name); DBMS_OUTPUT.PUT_LINE('Date of Birth: ' ||outer.date_of_birth); DBMS_OUTPUT.PUT_LINE('Child''s Name: '||child_name); DBMS_OUTPUT.PUT_LINE('Date of Birth: '||date_of_birth); END;END;/`

Page 11: 02 Writing Executable Statments

2-11 Copyright © 2006, Oracle. All rights reserved.

Determining Variable Scope

<<outer>>DECLARE sal NUMBER(7,2) := 60000; comm NUMBER(7,2) := sal * 0.20; message VARCHAR2(255) := ' eligible for commission';BEGIN DECLARE sal NUMBER(7,2) := 50000; comm NUMBER(7,2) := 0; total_comp NUMBER(7,2) := sal + comm; BEGIN message := 'CLERK not'||message; outer.comm := sal * 0.30; END; message := 'SALESMAN'||message;

END;/

1

2

Page 12: 02 Writing Executable Statments

2-12 Copyright © 2006, Oracle. All rights reserved.

Operators in PL/SQL

• Logical

• Arithmetic

• Concatenation

• Parentheses to control order of operations

• Exponential operator (**)

Same as in SQL}

Page 13: 02 Writing Executable Statments

2-13 Copyright © 2006, Oracle. All rights reserved.

Operators in PL/SQL

Examples

• Increment the counter for a loop.

• Set the value of a Boolean flag.

• Validate whether an employee number contains a value.

loop_count := loop_count + 1;

good_sal := sal BETWEEN 50000 AND 150000;

valid := (empno IS NOT NULL);

Page 14: 02 Writing Executable Statments

2-14 Copyright © 2006, 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

Page 15: 02 Writing Executable Statments

2Copyright © 2006, Oracle. All rights reserved.

Interacting withthe Oracle Server

Page 16: 02 Writing Executable Statments

2-16 Copyright © 2006, Oracle. 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.

• Control a transaction with the COMMIT, ROLLBACK, or SAVEPOINT command.

Page 17: 02 Writing Executable Statments

2-17 Copyright © 2006, Oracle. All rights reserved.

SELECT Statements in PL/SQL

Retrieve data from the database with a SELECT statement.

Syntax:SELECT select_listINTO {variable_name[, variable_name]...

| record_name} FROM table[WHERE condition];

Page 18: 02 Writing Executable Statments

2-18 Copyright © 2006, Oracle. All rights reserved.

Naming Conventions

DECLARE hire_date employees.hire_date%TYPE; sysdate hire_date%TYPE; employee_id employees.employee_id%TYPE := 176;

BEGIN SELECT hire_date, sysdate INTO hire_date, sysdate FROM employees WHERE employee_id = employee_id; END;/

Page 19: 02 Writing Executable Statments

2-19 Copyright © 2006, Oracle. All rights reserved.

Naming Conventions

• 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.

Page 20: 02 Writing Executable Statments

2-20 Copyright © 2006, Oracle. All rights reserved.

Manipulating Data Using PL/SQL

Make changes to database tables by using DML commands:

• INSERT• UPDATE• DELETE• MERGE

INSERT

UPDATE

DELETE

MERGE

Page 21: 02 Writing Executable Statments

2-21 Copyright © 2006, Oracle. All rights reserved.

Merging Rows

Insert or update rows in the copy_emp table to match the employees table.DECLARE

empno employees.employee_id%TYPE := 100;BEGINMERGE INTO copy_emp c USING employees e ON (e.employee_id = c.empno) WHEN MATCHED THEN UPDATE SET c.first_name = e.first_name, c.last_name = e.last_name, c.email = e.email, . . . WHEN NOT MATCHED THEN INSERT VALUES(e.employee_id, e.first_name, e.last_name, . . .,e.department_id);END;/

Page 22: 02 Writing Executable Statments

2-22 Copyright © 2006, Oracle. All rights reserved.

SQL Cursor

• A cursor is a pointer to the private memory area allocated by the Oracle server.

• 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

Page 23: 02 Writing Executable Statments

2-23 Copyright © 2006, Oracle. All rights reserved.

SQL Cursor Attributes for Implicit Cursors

Using SQL cursor attributes, you can test the outcome of your SQL statements.

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

Page 24: 02 Writing Executable Statments

2Copyright © 2006, Oracle. All rights reserved.

Writing Control Structures

Page 25: 02 Writing Executable Statments

2-25 Copyright © 2006, Oracle. All rights reserved.

Controlling Flow of Execution

for

loop

while

Page 26: 02 Writing Executable Statments

2-26 Copyright © 2006, Oracle. All rights reserved.

IF Statements

Syntax:

IF condition THEN statements;[ELSIF condition THEN statements;][ELSE statements;]END IF;

Page 27: 02 Writing Executable Statments

2-27 Copyright © 2006, Oracle. All rights reserved.

Simple IF Statement

DECLARE myage number:=31;BEGIN IF myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' I am a child '); END IF;END;/

Page 28: 02 Writing Executable Statments

2-28 Copyright © 2006, Oracle. All rights reserved.

IF THEN ELSE Statement

SET SERVEROUTPUT ONDECLAREmyage number:=31;BEGINIF myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' I am a child '); ELSE DBMS_OUTPUT.PUT_LINE(' I am not a child ');END IF;END;/

Page 29: 02 Writing Executable Statments

2-29 Copyright © 2006, Oracle. All rights reserved.

IF ELSIF ELSE ClauseDECLAREmyage number:=31;BEGINIF myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' I am a child '); ELSIF myage < 20 THEN DBMS_OUTPUT.PUT_LINE(' I am young '); ELSIF myage < 30 THEN DBMS_OUTPUT.PUT_LINE(' I am in my twenties'); ELSIF myage < 40 THEN DBMS_OUTPUT.PUT_LINE(' I am in my thirties'); ELSE DBMS_OUTPUT.PUT_LINE(' I am always young ');END IF;END;/

Page 30: 02 Writing Executable Statments

2-30 Copyright © 2006, Oracle. All rights reserved.

NULL Values in IF Statements

DECLAREmyage number;BEGINIF myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' I am a child '); ELSE DBMS_OUTPUT.PUT_LINE(' I am not a child ');END IF;END;/

Page 31: 02 Writing Executable Statments

2-31 Copyright © 2006, Oracle. All rights reserved.

CASE Expressions

• A CASE expression selects a result and returns it.

• To select the result, the CASE expression uses expressions. The value returned by these expressions is used to select one of several alternatives.

CASE selector WHEN expression1 THEN result1 WHEN expression2 THEN result2 ... WHEN expressionN THEN resultN [ELSE resultN+1]END;/

Page 32: 02 Writing Executable Statments

2-32 Copyright © 2006, Oracle. All rights reserved.

Searched CASE Expressions

DECLARE grade CHAR(1) := UPPER('&grade'); appraisal VARCHAR2(20);BEGIN appraisal := CASE WHEN grade = 'A' THEN 'Excellent' WHEN grade IN ('B','C') THEN 'Good' ELSE 'No such grade' END; DBMS_OUTPUT.PUT_LINE ('Grade: '|| grade || ' Appraisal ' || appraisal);END;/

Page 33: 02 Writing Executable Statments

2-33 Copyright © 2006, Oracle. All rights reserved.

Handling Nulls

When working with nulls, you can avoid some common mistakes by keeping in mind the following rules:

• Simple comparisons involving nulls always yield NULL.

• Applying the logical operator NOT to a null yields NULL.

• If the condition yields NULL in conditional control statements, its associated sequence of statements is not executed.

Page 34: 02 Writing Executable Statments

2-34 Copyright © 2006, Oracle. All rights reserved.

Logic Tables

Build a simple Boolean condition with a comparison operator.

AND

TRUE

FALSE

NULL

TRUE FALSE NULL

TRUE

NULL NULL

NULL

FALSE FALSE

FALSE

FALSE

FALSE

NOT

TRUE

FALSE

NULL

FALSE

TRUE

NULL

TRUE

NULL

OR TRUE FALSE NULL

TRUE

TRUE

TRUE

TRUETRUE

FALSE

NULL NULL

NULLFALSE

Page 35: 02 Writing Executable Statments

2-35 Copyright © 2006, Oracle. All rights reserved.

Iterative Control: LOOP Statements

• Loops repeat a statement or sequence of statements multiple times.

• There are three loop types:– Basic loop– FOR loop– WHILE loop

Page 36: 02 Writing Executable Statments

2-36 Copyright © 2006, Oracle. All rights reserved.

Basic Loops

Syntax:

LOOP statement1; . . . EXIT [WHEN condition];END LOOP;

Page 37: 02 Writing Executable Statments

2-37 Copyright © 2006, Oracle. All rights reserved.

WHILE Loops

Syntax:

Use the WHILE loop to repeat statements while a condition is TRUE.

WHILE condition LOOP statement1; statement2; . . .END LOOP;

Page 38: 02 Writing Executable Statments

2-38 Copyright © 2006, Oracle. All rights reserved.

FOR Loops

• Use a FOR loop to shortcut the test for the number of iterations.

• Do not declare the counter; it is declared implicitly.

• 'lower_bound .. upper_bound' is required syntax.

FOR counter IN [REVERSE] lower_bound..upper_bound LOOP statement1; statement2; . . .END LOOP;

Page 39: 02 Writing Executable Statments

2-39 Copyright © 2006, Oracle. All rights reserved.

FOR Loops

Guidelines

• Reference the counter within the loop only; it is undefined outside the loop.

• Do not reference the counter as the target of an assignment.

• Neither loop bound should be NULL.

Page 40: 02 Writing Executable Statments

2-40 Copyright © 2006, Oracle. All rights reserved.

Guidelines for Loops

• Use the basic loop when the statements inside the loop must execute at least once.

• Use the WHILE loop if the condition must be evaluated at the start of each iteration.

• Use a FOR loop if the number of iterations is known.

Page 41: 02 Writing Executable Statments

2-41 Copyright © 2006, Oracle. All rights reserved.

Nested Loops and Labels

• You can nest loops to multiple levels.

• Use labels to distinguish between blocks and loops.

• Exit the outer loop with the EXIT statement that references the label.

Page 42: 02 Writing Executable Statments

2-42 Copyright © 2006, Oracle. All rights reserved.

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; /

Page 43: 02 Writing Executable Statments

2-43 Copyright © 2006, Oracle. All rights reserved.

Class 2: Overview

This practice covers the following topics:

• Reviewing scoping and nesting rules

• Writing and testing PL/SQL blocks

• Selecting data from a table

• Inserting data into a table

• Updating data in a table

• Deleting a record from a table

• Performing conditional actions by using the IF statement