plsql part 1

37
1 OVERVIEW

Upload: sunilrgurav

Post on 21-Jul-2016

9 views

Category:

Documents


0 download

DESCRIPTION

PL/SQL fundamentals

TRANSCRIPT

Page 1: Plsql Part 1

1

OVERVIEW

Page 2: Plsql Part 1

2

About PL/SQL

PL/SQL is the procedural extension to SQL with design features of programming languages.

Data manipulation and query statements of SQL are included within procedural units of code.

Page 3: Plsql Part 1

Benefits of PL/SQL

Integration. Improved Performance. Portability Modularity of Program development.

3

Page 4: Plsql Part 1

4

Anonymous Block The Declaration section (optional). The Execution section (mandatory). The Exception Handling section (optional). [ DECLARE ... optional declaration statements ... ] variables, cursors, user-defined exceptions. BEGIN ... executable statements ... SQL statements PL/SQL statements [ EXCEPTION ... optional exception handler statements ... ] Actions to perform when errors occursEND;

Page 5: Plsql Part 1

5

Anonymous Block contd.Executing Statements and PL/SQL BlocksDECLAREv_variable VARCHAR2(5);BEGINSELECT column_name INTO v_variable FROM table_name;EXCEPTIONWHEN exception_name THEN. . . .END;

When PL/SQL Block is executed successfully, without unhandled

errors or compile errors, the message output should be as Follows“PL/SQL procedure successfully completed”

Page 6: Plsql Part 1

6

Types of VariablesPL/SQL variables Scalar

Scalar data types which hold a single value. CHAR,VARCHAR2,NUMBER etc. Composite

Composite data types, such as records, allow groups of fields to be defined and manipulated in PL/SQL blocks

ReferenceReference data type hold values, called pointers, that designate other program items.

LOBLOB data types hold values, called locators, that specify the location of large objects that are stored out of line.

Non-PL/SQL variables : Bind or host variables Bind variables can be used to pass run time values out of the

PL/SQL block back to the SQL environment.

Page 7: Plsql Part 1

7

Syntax

Identifier [constant] datatype [Not NULL] [: = | DEFAULT expr ];

Guidelines Follow naming Conventions Initialize variables designated as NOT NULL and

CONSTANT. Declare one identifier per line. Initialize identifiers by using the assignment

operator (:=) or the DEFUALT reserved word

Syntax and Guidelines for Declaring PL/SQL

variables

Page 8: Plsql Part 1

Composite Data Type Must contain one or more components of any Scalar, Record or INDEX

BY table data type called fields. Are convenient for fetching a row of data from table for processing.

ExampleType emp_record_type is RECORD ( last_name varchar2(25); job_id number(10) );emp_record emp_record_type;

8

Page 9: Plsql Part 1

The %Type and %Rowtype attribute

% Type Attribute Declare a variable according to - A database column definition - Another previously declared variables

Syntax Identifier Table.column%Type;Examples:v_name employees.last_name%TYPE;v_balance number;V_min_balance v_balance%TYPE := 10 ;

9

Page 10: Plsql Part 1

% RowType Attribute Declare a variable according to - a collection of columns in a database table or view.

Syntax Identifier Table%rowType;Examples:v_name employees%ROWTYPE;

10

Page 11: Plsql Part 1

LOB Data Type Variables CLOB (character Large Object) Used to store large blocks of single byte character data in the database in

line and out of line. BLOB (Binary Large Object ) Used to store large binary objects in the database in line and out of line. BFILE ( Binary file) Used to store large binary objects in OS files outside the database. NCLOB (National language large objects) Used to store large blocks of single byte or fixed width multibyte NCHAR

Unicode data in the database, in line and out of line.

11

Page 12: Plsql Part 1

12

Some symbols used.

Symbol Description; Semicolon: statement terminator.% Percent sign: attribute indicator (cursor attributes like %ISOPEN and indirect declaration attributes like

%ROWTYPE). Also used as multibyte wildcard symbol, as in SQL.

_ Single underscore: single-byte wildcard symbol, as in SQL : Colon: host variable indicator, such as :block.item in Oracle Forms ** Double asterisk: exponentiation operator < > and != "Not equals" || Double vertical bar: concatenation operator << and >> Label delimiters <= and >= Relational operators

:= Assignment operator => Association operator for positional notation  -- Double dash: single-line comment indicator /* and */ Beginning and ending multiple line comment block delimiters

Page 13: Plsql Part 1

13

Conditional control and Loops

IF <condition-1> THEN

<statements-1> ... ELSIF <condition-N> THEN

<statements-N> [ELSE

<else_statements>]END IF;

WHILE <condition> LOOP

<statement(s)> END LOOP;

FOR <loop index> IN <lowest no>..<highest no> LOOP

<statement(s)>END LOOP;

Page 14: Plsql Part 1

14

Explicit Cursors Assigning private work area for SQL statements.

PARSE Check Validity – Determine execution Plan.

BIND Association of values with placeholders.

OPEN Bind variables are attached to result set.

EXECUTE Statement run within SQL engine.

FETCH Retrieves the next row or record.

CLOSE Releases memory.

Page 15: Plsql Part 1

15

1 DECLARE 2 /* Explicit declaration of a cursor */ 3 CURSOR emptyp_cur IS 4 SELECT emptyp.type_desc 5 FROM employees emp, employee_type emptyp 6 WHERE emp.type_code = emptyp.type_code; 7 BEGIN 8 /* Check to see if cursor is already open. If not, open it. */ 9 IF NOT emptyp_cur%ISOPEN 10 THEN 11 OPEN emptyp_cur; 12 END IF; 13 14 /* Fetch row from cursor directly into an Oracle Forms item */ 15 FETCH emptyp_cur INTO :emp.type_desc; 16 17 /* Close the cursor */ 18 CLOSE emptyp_cur; 19 END;

Page 16: Plsql Part 1

16

Cursor contd. Attribute Description

%ISOPEN TRUE if cursor is open.FALSE if cursor is not open.

%FOUND INVALID_CURSOR is raised if cursor has not been OPENed. NULL before the first fetch. TRUE if record was fetched successfully.FALSE if no row was returned.INVALID_CURSOR if cursor has been CLOSEd.

%NOTFOUND INVALID_CURSOR is raised if cursor has not been OPENed.NULL before the first fetch. FALSE if record was fetched successfully.TRUE if no row was returned.INVALID_CURSOR if cursor has been CLOSEd.

%ROWCOUNT INVALID_CURSOR is raised if cursor has not been OPENed.The number of rows fetched from the cursor.INVALID_CURSOR if cursor has been CLOSEd.

Page 17: Plsql Part 1

17

Revisiting the FOR loop.

DECLARE CURSOR occupancy_cur IS SELECT pet_id, room_number FROM occupancy WHERE occupied_dt = SYSDATE; occupancy_rec occupancy_cur%ROWTYPE; BEGIN OPEN occupancy_cur; LOOP FETCH occupancy_cur INTO occupancy_rec; EXIT WHEN occupancy_cur%NOTFOUND; update_bill (occupancy_rec.pet_id, occupancy_rec.room_number); END LOOP; CLOSE occupancy_cur; END;

Cursor without FOR loop implementation.

Page 18: Plsql Part 1

18

DECLARE CURSOR occupancy_cur IS SELECT pet_id, room_number FROM occupancy WHERE occupied_dt = SYSDATE;BEGIN FOR occupancy_rec IN occupancy_cur LOOP update_bill (occupancy_rec.pet_id, occupancy_rec.room_number); END LOOP;END;

FOR Loop cursor.

Page 19: Plsql Part 1

19

PL/SQL Blocks Stored Procedures

A named PL/SQL block that performs one or more actions and is called as an executable PL/SQL statement. You can pass information into and out of a procedure

through its parameter list.

CREATE OR REPLACE PROCEDURE <name> [ ( parameter [, parameter ... ] ) ]IS [declaration statements]

BEGIN <executable-statements>

[ EXCEPTION exception handler statements]

END [ name ];

Page 20: Plsql Part 1

20

CREATE OR REPLACE PROCEDURE show_emp( p_empno IN NUMBER, rec OUT NUMBER)IS records NUMBER(3); BEGIN FOR c1 IN (SELECT ename,job,sal,comm FROM emp WHERE empno = p_empno) LOOP DBMS_OUTPUT.PUT_LINE('Name: ' || c1.ename); DBMS_OUTPUT.PUT_LINE('Job: ' || c1.job); DBMS_OUTPUT.PUT_LINE('Salary: ' || c1.sal); DBMS_OUTPUT.PUT_LINE('Commission: ' || c1.comm); records := records + 1; END LOOP; rec := records; END show_emp;/

Stored Procedures contd.

1) From the SQL prompt.EXECUTE [or EXEC] :count := show_emp (10616621);

2) Within another procedure – simply use the procedure name. show_emp (10616621, count);

Page 21: Plsql Part 1

21

1) IN : These types of parameters are used to send values to stored procedures.

2) OUT : These types of parameters are used to get values from stored procedures.

3) IN OUT: These types of parameters are used to send values and get values from stored procedures.

Positional vs. Notational parameters

CREATE OR REPLACE PROCEDURE show_emp(ename varchar2, eno varchar2)ISBEGIN

/***<procedure body>***/END;/

show_emp (eno => 10616621, ename =>'Arjun');

show_emp ('Arjun', 10616621);

Parameters

Page 22: Plsql Part 1

22

Functions A function is a module that returns a value.

Unlike a procedure, which is a standalone executable statement, a call to a function can only be part of an executable statement.

CREATE OR REPLACE FUNCTION name [ ( parameter [, parameter ... ] ) ] RETURN <return_datatype>IS [ declaration statements ]

BEGIN executable statements

[ EXCEPTION exception handler statements ]

END [ name ];

Page 23: Plsql Part 1

23

Functions contd. CREATE OR REPLACE FUNCTION tot_sales (company_id_in IN company.company_id%TYPE,

status_in IN order.status%TYPE := NULL)RETURN NUMBERIS return_value NUMBER; CURSOR sales_cur (status_in status_code%TYPE)

IS SELECT SUM(amount*discount) FROM item WHERE EXISTS (SELECT 'X' FROM order

order.order_id = item.order_id AND company_id = company_id_in AND status_code LIKE status_in);

BEGINOPEN sales_cur (status_in);FETCH sales_cur INTO return_value;IF sales_cur%NOTFOUNDTHEN CLOSE sales_cur; RETURN NULL;ELSE CLOSE sales_cur; RETURN return_value;END IF;

END tot_sales;/

Page 24: Plsql Part 1

24

Calling a Function

• Call tot_sales to assign a value to a local PL/SQL variable:sales_for_1995 := tot_sales (1504, 'C');

• Use a call to tot_sales to set a default value for a variable:

DECLARE sales_for_1995 NUMBER DEFAULT tot_sales (1504, 'C');BEGIN

• Use tot_sales directly in an expression:

IF tot_sales (275, 'O') > 10000THEN...

• SELECT Query:SELECT company_id, tot_sales (company_id, ‘O')FROM company;

Page 25: Plsql Part 1

25

TriggersA database triggers is stored PL/SQL program unit associated with a specific database table or view.

The code in the trigger defines the action the database needs to perform whenever some database manipulation (INSERT, UPDATE, DELETE) takes place.

A triggering event A trigger constraint (Optional)

Trigger action

CREATE OR REPLACE TRIGGER Print_salary_changes BEFORE DELETE OR INSERT OR UPDATE ON Emp_tab FOR EACH ROW WHEN (new.Empno > 0)DECLARE sal_diff number;BEGIN sal_diff := :new.sal - :old.sal; dbms_output.put_line ('Old salary: ' || :old.sal); dbms_output.put_line (' New salary: ' || :new.sal); dbms_output.put_line(' Difference ' || sal_diff);END;/

Page 26: Plsql Part 1

26

Types of TriggersRow level triggers Statement level triggers

BEFORE statement triggers AFTER statement triggers

LOGON / LOGOFF triggersINSTEAD OF triggers

FOR EACH ROW

BEFORE | AFTER

INSERT | [OR] UPDATE | [OR] DELETE

DDL triggers

INSTEAD OF INSERT ON manager_info

FOR EACH ROW

AFTER LOGON ON DATABASE | BEFORE LOGOFF ON

DATABASE

BEFORE | AFTER

CREATE | ALTER | DROP

Page 27: Plsql Part 1

27

An error generated by the system (such as “Unique constraint violation") An error caused by a user action A warning issued by the application to the user

Exception

EXCEPTION WHEN exception_name [ OR exception_name ... ] THEN <executable statements>END;

The Exception Section An English-like TranslationEXCEPTION WHEN NO_DATA_FOUND THEN executable_statements1;

If the NO_DATA_FOUND exception was raised, then execute thefirst set of statements.

WHEN payment_overdue THEN executable_statements2;

If the payment is overdue, then execute the second set ofstatements.

WHEN OTHERS THEN executable_statements3;END;

If any other exception is encountered, then execute the thirdset of statements.

Page 28: Plsql Part 1

28

Types of Exception

• Named system exceptions. Exceptions that have been given names by PL/SQL and raised as a result of an error in PL/SQL or RDBMS processing.

EXCEPTION WHEN CURSOR_ALREADY_OPEN THEN CLOSE my_cursor;

END;

• Named programmer-defined exceptions. Exceptions that are raised as a result of errors in your application code. You give these exceptions names by declaring them in the declaration section. You then raise the exceptions explicitly in the program.

PROCEDURE calc_annual_sales (company_id_in IN company.company_id%TYPE)IS invalid_company_id EXCEPTION; BEGIN <... body of executable statements ...>EXCEPTION WHEN invalid_company_id THEN ...END;

Page 29: Plsql Part 1

29

• Unnamed system exceptions. Exceptions that are raised as a result of an error in PL/SQL or RDBMS processing but have not been given names by PL/SQL. Only the most common errors are so named; the rest have numbers and can be assigned names with the special PRAGMA EXCEPTION_INIT syntax. Consider the below Error DescriptionORA-02292 : integrity constraint (string.string) violated - child record found

Cause : attempted to delete a parent key value that had a foreign key dependency.Action : delete dependencies first then parent or disable constraint.

PROCEDURE delete_company (company_id_in IN NUMBER)IS /* Declare the exception. */ still_have_employees EXCEPTION; /* Associate the exception name with an error number. */ PRAGMA EXCEPTION_INIT (still_have_employees, -2292);BEGIN /* Try to delete the company. */ DELETE FROM company WHERE company_id = company_id_in;EXCEPTION /* If child records were found, this exception is raised! */ WHEN still_have_employees THEN DBMS_OUTPUT.PUT_LINE (' Please delete employees for company first.');END;

Page 30: Plsql Part 1

30

• Unnamed programmer-defined exceptions. Exceptions that are defined and raised in the server by the programmer.

The programmer provides both an error number (between -20000 and -20999) and an error message, and raises that exception with a call to RAISE_APPLICATION_ERROR, a system defined error handling procedure.

The error, along with its message, is propagated back to the client-side application.

CREATE OR REPLACE TRIGGER minimum_age_checkBEFORE INSERT ON employeeFOR EACH ROWBEGIN IF ADD_MONTHS

(:new.birth_date, 18*12) > SYSDATE THEN RAISE_APPLICATION_ERROR (-20001, 'Employees

must at least eighteen years of age.'); END IF;END;

Page 31: Plsql Part 1

31

PackagesA package is a group of procedures, functions,

variables and SQL statements created as a single unit. It is used to store together related objects.

A package has two parts, Package Specification or package header and Package Body.

ComponentsCursorsVariables (scalars, records, tables, etc.)Exception namesPL/SQL table and record TYPE statementsProcedures and Functions

Advantages of Using PackageInformation Hiding Object-Oriented DesignTop-Down Design Object Persistence Performance Improvement

Page 32: Plsql Part 1

32

PACKAGE package_nameIS [ declarations of variables and types ] [ specifications of cursors ] [ specifications of modules ]END [ package_name ];

Packages contd.

Specification

BodyPACKAGE BODY package_nameIS [ declarations of variables and types ] [ specification and SELECT statement of cursors ] [ specification and body of modules ][ BEGIN executable statements ][ EXCEPTION exception handlers ]END [ package_name ];

Page 33: Plsql Part 1

33

Data PrivacyPublic

Defined in the specification. A public element can be referenced from other programs and PL/SQL blocks.

Private Defined only in the body of the package, but does not appear in the specification. A private element cannot be referenced outside of the package. Any other element of the package may, however, reference and use a private element.

Page 34: Plsql Part 1

34

CREATE OR REPLACE PACKAGE update_planned_hrsIS Planned_hours NUMBER(4); PROCEDURE set_new_planned (p_emp_id IN NUMBER, p_project_id IN NUMBER, p_hours IN NUMBER); FUNCTION existing_planned (p_emp_id IN NUMBER, p_project_id IN NUMBER)

RETURN NUMBER; END update_planned_hrs;/CREATE OR REPLACE PACKAGE BODY update_planned_hrsIS

PROCEDURE set_new_planned (p_emp_id IN NUMBER, p_project_id IN NUMBER, p_hours IN NUMBER)ISBEGIN UPDATE employee_on_activity e SET e.ea_planned_hours = p_hours WHERE e.ea_emp_id = p_emp_id AND e.ea_proj_id = p_project_id; EXCEPTION WHEN NO_DATA_FOUND THEN RAISE_APPLICATION_ERROR (-20100, 'No such employee or project'); END set_new_planned;

--continued to next slide

The purpose of the package is to update the planned hours of an employee, to a project. The employee is constrained to the passed in parameter. An error is raised if the employee or project does not exist.

Page 35: Plsql Part 1

35

FUNCTION existing_planned (p_emp_id IN NUMBER, p_project_id IN NUMBER) RETURN NUMBERIS existing_hours NUMBER(4);

BEGIN SELECT ea.ea_planned_hours INTO existing_hours FROM employee_on_activity e WHERE e.ea_emp_id = p_emp_id AND e.ea_proj_id = p_project_id; RETURN (existing_hours); EXCEPTION WHEN NO_DATA_FOUND THEN RAISE_APPLICATION_ERROR (-20100, 'No such employee or project'); END existing_planned;END update_planned_hrs; --ending the package/

Page 36: Plsql Part 1

36

Accessing components

EXEC update_planned_hrs.set_new_planned (‘1001’, ‘MonteCarlo’, 9);

SELECT update_planned.existing_planned (‘1001’, ‘MonteCarlo’) FROM DUAL;

Page 37: Plsql Part 1

37