advanced databases

70
1 Advanced Databases PL/SQL Anonymous Blocks

Upload: gurit

Post on 07-Jan-2016

40 views

Category:

Documents


1 download

DESCRIPTION

Advanced Databases. PL/SQL Anonymous Blocks. What is PL/SQL?. Procedural programming language Uses detailed instructions Processes statements sequentially Combines SQL commands with procedural instructions Used to perform sequential processing using an Oracle database. PL/SQL Variables. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Advanced Databases

1

Advanced Databases

PL/SQL Anonymous Blocks

Page 2: Advanced Databases

2

Procedural programming language Uses detailed instructions Processes statements sequentially

Combines SQL commands with procedural instructions

Used to perform sequential processing using an Oracle database

What is PL/SQL?

Page 3: Advanced Databases

3

PL/SQL Variables Variable names must follow the Oracle

naming standard Can use reserved words (BEGIN, NUMBER)

and table names for variable names, but is not a good practice

Make variable names descriptive Use lower-case letters, and separate

words with underscores Example: current_s_id

Page 4: Advanced Databases

4

Declaring PL/SQL Variables PL/SQL is a strongly-typed

language All variables must be declared prior to

use Syntax for declaring a variable:variable_name data_type_declaration;

Example:current_s_id NUMBER(6);

Page 5: Advanced Databases

5

PL/SQL Data Types Scalar

References a single value Composite

References a data structure Reference (Not Required)

References a specific database item LOB (Not Required)

References a large binary object

Page 6: Advanced Databases

6

Scalar Data Types Database scalar data types:

VARCHAR2 CHAR DATE LONG NUMBER

Non-database scalar data types: Integers: BINARY_INTEGER, INTEGER, INT,

SMALLINT Decimal numbers: DEC, DECIMAL, DOUBLE,

PRECISION, NUMERIC, REAL BOOLEAN

Page 7: Advanced Databases

7

Composite Data Types Reference multiple data elements,

such as a record Types:

RECORD TABLE VARRAY

Tabular structure that can expand or contract as needed

Page 8: Advanced Databases

8

Reference Data Types (Not Required)

Reference a database item Assume data type of item

%TYPE: assumes data type of field %ROWTYPE: assumes data type of

entire row

Page 9: Advanced Databases

9

DECLAREVariable declarations

BEGINProgram statements

EXCEPTIONError-handling statements

END;

BodyBody

Variable Declarations

Variable Declarations

ExceptionSection

ExceptionSection

PL/SQL Program Structure

Page 10: Advanced Databases

10

May span multiple text editor lines

Each line ends with a semicolon

Text is not case sensitive

PL/SQL Program Lines

Page 11: Advanced Databases

11

Block of comments are delimited with /* */

/* <comment that spans more than one line of code> */

Single comment line starts with 2 hyphens-- comment on a single line

Comment Statements

Page 12: Advanced Databases

12

** Exponentiation 2 ** 3 8

* Multiplication 2 * 3 6

/ Division 9/2 4.5

+ Addition 3 + 2 5

- Subtraction 3 – 2 1

- Negation -5 Negative 5

Example ResultArithmetic Operators

Page 13: Advanced Databases

13

Assignment operator: := Variable being assigned to a new

value is on left side of assignment operator

New value is on right side of operator

student_name := ‘John Miller’;

student_name := current_student;

Assignment Statements

Page 14: Advanced Databases

14

Normally PL/SQL is used with other Oracle utilities such as forms or reports

You will learn to use PL/SQL in SQL*Plus Command to activate memory buffer in

SQL*Plus to enable output from PL/SQL programs:

SQL> SET SERVEROUTPUT ON SIZE buffer_size;

SQL> SET SERVEROUTPUT ON SIZE 4000;

Displaying PL/SQL Outputin SQL*Plus

Page 15: Advanced Databases

15

Command to output data from a PL/SQL program in SQL*Plus:

DBMS_OUTPUT.PUT_LINE(‘output string’);

DBMS_OUTPUT.PUT_LINE(‘Current Output:’);

Displaying PL/SQL ProgramOutput in SQL*Plus

Page 16: Advanced Databases

16

Copy program code from Notepad to SQL*Plus

Type / to execute

Executing a PL/SQL Programin SQL*Plus

Page 17: Advanced Databases

17

TO_DATE: character string to DATETO_DATE(‘07/14/01’, ‘MM/DD/YY’);

TO_NUMBER: character string to NUMBERTO_NUMBER(‘2’);

TO_CHAR: NUMBER or DATE to character string

TO_CHAR(2);

TO_CHAR(SYSDATE, ‘MM/DD/YYYY HH:MI’);

PL/SQL Data Type Conversion Functions

Page 18: Advanced Databases

18

Concatenating strings: joining 2 or more character strings into a single string

Concatenation operator: ||s_first_name := ‘Sarah’

s_last_name := ‘Miller’

s_full_name := s_first_name || ‘ ’ || s_last_name

Character String Functions

Page 19: Advanced Databases

19

RTRIM: removes blank trailing spacescust_address := RTRIM(cust_address);

LENGTH: returns string length (number of characters)

address_length := LENGTH(cust_address); UPPER, LOWER: changes characters to all

upper or lower cases_name := UPPER(s_name);s_name := LOWER(s_name);

PL/SQL Character String Functions

Page 20: Advanced Databases

20

INSTR: searches a string and looks for a matching substring and returns its starting positionstarting_position := INSTR(string_being_searched, search_string>);

blank_position := INSTR(‘Sarah Miller’, ‘ ’);

PL/SQL Character String Functions

Page 21: Advanced Databases

21

SUBSTR: extracts a specific number of characters from a string, starting at a given pointextracted_string := SUBSTR(string_being_searched, starting_point, number_of_characters_to_extract);

s_first_name := SUBSTR(‘Sarah Miller’, 1,5);

PL/SQL Character String Functions

Page 22: Advanced Databases

22

Syntax error Does not follow language guidelines Causes a PLS- compile error Examples: misspelling a reserved

word, using a function incorrectly Logic error

Program compiles correctly, but does not give correct output

Debugging PL/SQL Programs

Page 23: Advanced Databases

23

Isolate the line that is causing the error This may be before or after the line

that is flagged by the compiler Comment out lines as necessary

until program runs One error may cause several

cascading errors, so re-run program after fixing each error

Locating and Correcting Syntax Errors

Page 24: Advanced Databases

24

1. Identify the output variable(s) that have the error.

2. Identify the inputs and calculations that contribute to the error.

3. Display the values of the inputs using DBMS_OUTPUT commands.

4. Take a break and look at it again later.5. Ask a fellow student for help.6. Ask your instructor for help.

Locating and Fixing Logic Errors

Page 25: Advanced Databases

25

NULL Values in Assignment Statements Until a value is assigned to a

variable, the variable’s value is NULL Performing an arithmetic value on a

NULL value always results in a NULL value

Advice: Always initialize variable values

Page 26: Advanced Databases

26

IF/END IF:IF condition THEN

program statementsEND IF;

IF/ELSE/END IF:IF condition THEN

program statementsELSE

alternate program statements

END IF;

IF/THEN

PL/SQL Selection Structures

Page 27: Advanced Databases

27

IF/ELSIF:IF condition1 THEN

program statements;ELSIF condition2 THENalternate program statements;

ELSIF condition3 THENalternate program statements;

. . .ELSEalternate program statements;

END IF;

PL/SQL Selection Structures

Page 28: Advanced Databases

28

Operator Description Example

= Equal Count = 5

<>, != Not Equal Count <> 5

> Greater Than Count > 5

< Less Than Count < 5

>= Greater Than or Equal To

Count >= 5

<= Less Than or Equal To Count <= 5

PL/SQL Comparison Operators

Page 29: Advanced Databases

29

Evaluating NULL Conditions in IF/THEN Structures If a condition evaluates as NULL,

then it is FALSE How can a condition evaluate as

NULL? It uses a BOOLEAN variable that has

not been initialized It uses any other variable that has not

been initialized

Page 30: Advanced Databases

30

SQL Command Category

Purpose Examples Can be used in PL/SQL

Data Definition Language (DDL)

Change database structure

CREATE, ALTER, GRANT, REVOKE

No

Data Manipulation Language (DML)

View or change data

SELECT, INSERT, UPDATE, DELETE

Yes

Transaction Control

Create logical transactions

COMMIT, ROLLBACK

Yes

Using SQL Commands in PL/SQL Programs

Page 31: Advanced Databases

31

Loop: repeats one or more program statements multiple times until an exit condition is reached Pretest loop: exit condition is tested

before program statements are executed

Posttest loop: exit condition is tested after program statements are executed

PL/SQL Loops

Page 32: Advanced Databases

32

LOOP

program statements

IF condition THEN

EXIT;

END IF;

more program statements

END LOOP;

LOOP … EXIT

Pretest OR Posttest

Pretest OR Posttest

LOOP … EXIT Loop

Page 33: Advanced Databases

33

LOOPprogram statementsEXIT WHEN condition;

END LOOP;

Posttest Posttest

LOOP … EXIT WHEN Loop

Page 34: Advanced Databases

34

WHILE … LOOP

WHILE conditionLOOP

program statementsEND LOOP;

Pretest Pretest

WHILE Loop

Page 35: Advanced Databases

35

FOR counter_variable IN start_value .. end_valueLOOP program statementsEND LOOP;

Preset number of iterations

Preset number of iterations

Numeric FOR Loop

Page 36: Advanced Databases

36

Cursors Pointer to a server memory

location Contains information about a SQL

command in a PL/SQL program Called the command’s context area

Page 37: Advanced Databases

37

Cursor

contextarea

active setCID CALLID CNAME CCREDIT

1 MIS 101 Intro. to Info. Systems 32 MIS 301 Systems Analysis 33 MIS 441 Database Management 34 CS 155 Programming in C++ 35 MIS 451 Client/Server Systems 3

Number of rows

processed

Parsed commandstatement

Database Server Memory

Cursors

Page 38: Advanced Databases

38

Implicit Explicit

Types of Cursors

Page 39: Advanced Databases

39

Created automatically every time you use an INSERT, UPDATE, DELETE, or SELECT command

Doesn’t need to be declared Can be used to assign the output of a

SELECT command to one or more PL/SQL variables

Can only be used if query returns one and only one record

Implicit Cursors

Page 40: Advanced Databases

40

SELECT field1, field2, …

INTO variable1, variable2, …

FROM tablename

WHERE search_condition_that_will_

return_a_single_record;

Implicit Cursor Syntax

Page 41: Advanced Databases

41

Must be declared in program DECLARE section

Can be used to assign the output of a SELECT command to one or more PL/SQL variables

Can be used if query returns multiple records or no records

Explicit Cursors

Page 42: Advanced Databases

42

Declare the cursor Open the cursor Fetch the cursor result into

PL/SQL program variables Close the cursor

Using an Explicit Cursor

Page 43: Advanced Databases

43

Declaring an Explicit Cursor

DECLARE

CURSOR cursor_name IS SELECT_statement;

Page 44: Advanced Databases

44

Opening an Explicit Cursor

OPEN cursor_name;

Page 45: Advanced Databases

45

Fetching Explicit Cursor Records

FETCH cursor_name INTO variable_name(s);

Page 46: Advanced Databases

46

Closing an Explicit Cursor

CLOSE cursor_name;

Page 47: Advanced Databases

47

Processing an Explicit Cursor LOOP ..EXIT WHEN approach:OPEN cursor_name;

LOOP

FETCH cursor_name INTO variable_name(s);

EXIT WHEN cursor_name%NOTFOUND:

END LOOP;

CLOSE cursor_name;

Page 48: Advanced Databases

48

Processing an Explicit Cursor Cursor FOR Loop approach:

FOR variable_name(s) in cursor_name LOOP

additional processing statements;

END LOOP;

Page 49: Advanced Databases

49

Attribute Return Value

%NOTFOUND TRUE when no rows left to fetch; FALSE when rows left to fetch

%FOUND TRUE when rows left to fetch; FALSE when no rows left to fetch

%ROWCOUNT Number of rows a cursor has fetched so far

%ISOPEN TRUE if cursor is open and FALSE is cursor is closed

Explicit Cursor Attributes

Page 50: Advanced Databases

50

Using Reference Data Types in Explicit Cursor Processing

Declaring a ROWTYPE reference variable:

DECLARE

reference_variable_name cursor_name%ROWTYPE;

Referencing a ROWTYPE reference variable:

reference_variable_name.database_field_name

Page 51: Advanced Databases

51

PL/SQL Example1DECLARE Emp_name VARCHAR2(10); Cursor c1 IS SELECT Ename FROM Emp_tab WHERE Deptno = 20;BEGIN OPEN c1; LOOP FETCH c1 INTO Emp_name; EXIT WHEN c1%NOTFOUND; DBMS_OUTPUT.PUT_LINE(Emp_name); END LOOP;END;

Page 52: Advanced Databases

52

PL/SQL Example2DECLARE Emp_number INTEGER := 9999; Emp_name emp.empname%type;BEGIN SELECT Ename INTO Emp_name FROM Emp_tab WHERE Empno = Emp_number; -- no such number DBMS_OUTPUT.PUT_LINE('Employee name is ' || Emp_name);EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE('No such employee: ' || Emp_number);END;

Page 53: Advanced Databases

53

Composed into two components: Primary Key Column of Scalar or record type

Increased dynamically Similar to Arrays in programming languages Known as Objects of type tables SyntaxTYPE typename is TABLE OF[column_type | variable%type][INDEX BY BINARY_IINTEGER];Indentifier type_name;

PL/SQL Tables

Page 54: Advanced Databases

54

PL/SQL Tables Declaration There are two steps in the

declaration of a PL/SQL table. First, you must define the table

structure using the TYPE statement. Second, once a table type is created,

you then declare the actual table.

Page 55: Advanced Databases

55

PL/SQL Table Declaration Example:DECLARE-- Table structure definitionTYPE EmpNameType IS TABLE OFEmp.empname%TYPEINDEX BY BINARY_INTEGER;-- Create the actual tableEmpTab EmpNameType;SupTab EmpNameType;BEGIN

NULL; -- ...END;

Page 56: Advanced Databases

56

Referencing and Modifying PL/SQL table rows In order to specify a particular row in a PL/SQL

table, you must name the table and the index. Syntax: <table_name>(<index_value>)

The datatype of the index value must be compatible with the BINARY_INTEGER datatype.

You assign values to a row using the standard assignment operator.

Referencing a nonexistent row raises the NO_DATA_FOUND exception.

Page 57: Advanced Databases

57

Referencing and Modifying PL/SQL table rows Example:

DECLARE

CURSOR c_Ename ISSELECT empname, empnoFROM empORDER BY empname;

TYPE type_Ename_tab IS TABLE OF emp.empname%TYPEINDEX BY BINARY_INTEGER;

tab_Ename type_Ename_tab;v_Ename_counter NUMBER := 0;

BEGINFOR r_Ename IN c_EnameLOOP v_Ename_counter := v_Ename_counter + 1;

tab_Ename(v_Ename_counter):= r_Ename.empname;END LOOP;

FOR i_Ename IN 1 .. v_Ename_counterLOOP DBMS_OUTPUT.PUT_LINE('Here is a name: '|| Tab_Ename(i_Ename));END LOOP;

END; 

Page 58: Advanced Databases

58

PL/SQL TABLE ATTRIBUTES Here are seven PL/SQL table attributes you can use to gain

informationabout a PL/SQL table or to modify a row in a PL/SQL table:• DELETE—Deletes rows in a table.• EXISTS—Return TRUE if the specified entry exists in the table.• COUNT—Returns the number of rows in the table.• FIRST—Returns the index of the first row in the table.• LAST—Returns the index of the last row in the table.• NEXT—Returns the index of the next row in the table after the

specified row.• PRIOR—Returns the index of the previous row in the table be-for

the specified row.

Page 59: Advanced Databases

59

PL/SQL Table Attributes – How to use them? PL/SQL table attributes are used with the following syntax:

<table_name>.<attribute> If you declare a PL/SQL table named t_emp then you get a rowcount

for the table as follows:v_count := t_emp.count;

The DELETE, EXISTS, NEXT and PRIOR attributes function differently than the other attributes.These two generally operate on one row at a time, so you mustadd the following syntax:<TableName>.<attribute>(<IndexNumber>[,<IndexNumber>])

Examples:t.emp.delete deletes all rows from the t_emp table, whereast_emp.delete(15) deletes the fifteenth row of the t_emp table.

Likewise, t_emp.exists(10) returns a value of true if there is a tenth row and a value of false if there is not.The EXISTS attribute can be used to determine if a particular index valueexists in the PL/SQL table or not.

NEXT and PRIOR is used in the same manner

Page 60: Advanced Databases

60

PL/SQL Exception Handling All error handling statements are

placed in the EXCEPTION program block

Exception handler: program command that provides information about an error, and suggest correction actions

Page 61: Advanced Databases

61

Common errors that have been given predefined names that appear instead of error numbers

Error Code Exception Name Description ORA-00001 DUP_VAL_ON_INDEX Unique constraint violated ORA-01001 INVALID_CURSOR Illegal cursor operation

ORA-01403 NO_DATA_FOUND Query returns no records

ORA-01422 TOO_MANY_ROWS Query returns more rows than expected

ORA-01476 ZERO_DIVIDE Division by zero ORA-01722 INVALID_NUMBER Invalid numeric conversion

ORA-06502 VALUE_ERROR Error in arithmetic or numeric function operation

Predefined Exceptions

Page 62: Advanced Databases

62

Exception Handler SyntaxFor Predefined Exceptions

WHEN exception1_name THEN

exception handling statements;

WHEN exception2_name THEN

exception handling statements;

WHEN OTHERS THEN

exception handling statements;

Page 63: Advanced Databases

63

Less-common errors that have not been given predefined names

ORA- error code appears Exception handler tests for ORA-

error code and provides alternate error message

Undefined Exceptions

Page 64: Advanced Databases

64

Errors that will not cause a run-time error, but will violate business rules(i.e. they are created for logical errors)

Programmer creates a custom error message

User-Defined Exceptions

Page 65: Advanced Databases

65

Nested PL/SQL Program Blocks An inner

program block can be nested within an outer program block

DECLARE variable declarationsBEGIN program statements

EXCEPTION error handling statementsEND;

DECLARE variable declarationsBEGIN program statementsEXCEPTION error handling statementsEND;

Inner block

Outer block

Page 66: Advanced Databases

66

Exception Handling in Nest Program Blocks If an exception is raised and

handled in an inner block, program execution resumes in the outer block

Page 67: Advanced Databases

67

DECLARE variable declarationsBEGIN program statements

additional program statementsEXCEPTION error handling statementsEND;

Exception Handling in Nested Program Blocks

DECLARE exception_ABEGIN RAISE exception_AEXCEPTION exception_A error handlerEND;

Exception is raised andhandled in inner block

Program executionresumes here

Page 68: Advanced Databases

68

Exception Handling in Nested Program Blocks Exceptions raised in inner blocks

can be handled by exception handlers in outer blocks

Page 69: Advanced Databases

69

Example of a USER-DEFINED ExceptionDeclare

huge_quantity exception;V_qty number(10);v_msg varchar2(100);

Beginv_qty := &V_qty;if v_qty > 1000 then v_msg := ‘very huge quantity’;

raise huge_quantity; else v_msg := ‘Good’; end if;

dbms_output.put_line (v_msg);Exception when huge_quantity then dbms_output.put_line (v_msg);End;

Page 70: Advanced Databases

70

Example of a USER-DEFINED Exception (Giving an error number between -20000 to -20999)

Declarehuge_quantity exception;V_qty number(10);v_msg varchar2(100);

Beginv_qty := &V_qty;if v_qty > 1000 then v_msg := ‘very huge quantity’;

raise huge_quantity; else v_msg := ‘Good’; end if;

dbms_output.put_line (v_msg);Exception when huge_quantity then

raise_application_error (-20100, v_msg);End;