19
Ashish Raghute, IT Director, Fleetwood Enterprises Introduction to Procedural SQL (PL/SQL)

Ashish Raghute, IT Director, Fleetwood Enterprises Introduction to Procedural SQL (PL/SQL)

Embed Size (px)

Citation preview

Page 1: Ashish Raghute, IT Director, Fleetwood Enterprises Introduction to Procedural SQL (PL/SQL)

Ashish Raghute, IT Director, Fleetwood Enterprises

Introduction to Procedural SQL (PL/SQL)

Page 2: Ashish Raghute, IT Director, Fleetwood Enterprises Introduction to Procedural SQL (PL/SQL)

PL/SQL Database Programming

7:30 am – 11:30 am

1. Developing PL/SQL programs

2. Procedures

3. Functions

4. Database Triggers

Page 3: Ashish Raghute, IT Director, Fleetwood Enterprises Introduction to Procedural SQL (PL/SQL)

What is PL/SQL ? PL/SQL – Procedural Language/SQL

Introduction –

Has features of a procedural language like COBOL or C, such as conditional branching, looping, variables etc.

Used for complex data processing, such as data conversion and BOM back-flush processing etc.

Also used for writing database triggers.

Most server-side PL/SQL code exists mainly as stored procedures or functions. Some of it exists as DB Triggers.

Stored procedures are executed with the privilege of its creator.

You can hide confidential code from end-users and just provide them with controlled access to sensitive information using stored procedures.

Lowers network traffic, saves on parsing time.

Can be written using SQL*Plus or Oracle Procedure Builder or other tools like Toad.

Page 4: Ashish Raghute, IT Director, Fleetwood Enterprises Introduction to Procedural SQL (PL/SQL)

PL/SQL structure

The basic unit in PL/SQL is a block. All PL/SQL programs are made up of blocks, which can be nested within each other. Typically, each block performs a logical action in he program. A block has the following structure:

DECLARE    

/* Declarative section: variables, types, and local subprograms. */     BEGIN    

/* Executable section: procedural and SQL statements go here. */    /* This is the only section of the block that is required. */    EXCEPTION    

/* Exception handling section: error handling statements go here. */     END;

Page 5: Ashish Raghute, IT Director, Fleetwood Enterprises Introduction to Procedural SQL (PL/SQL)

Only the executable section is required. The other sections are optional. The only SQL statements allowed in a PL/SQL program are SELECT, INSERT, UPDATE, DELETE and several other data manipulation statements plus some transaction control. Data definition statements like CREATE, DROP, or ALTER are not allowed. The executable section also contains constructs such as assignments, branches, loops, procedure calls, and triggers, which are all described below (except triggers). PL/SQL is not case sensitive. C style comments (/* ... */) may be used.

Lets write our first PL/SQL program:

DECLARE     a NUMBER := 3; BEGIN     a := a + 1; dbms_output.put_line(a); END;

Exec dbms_output.enable;Set serveroutput on.run;

We will learn about the EXCEPTION handling in later slides.

PL/SQL structure

Page 6: Ashish Raghute, IT Director, Fleetwood Enterprises Introduction to Procedural SQL (PL/SQL)

Lets look at some PL/SQL data types:

Examples of variable declarations are given below :

V_NUM1 NUMBER NOT NULL := 10109; NUM8 NUMBER(3,1); XYZ NUMBER(2,2) := 31.8; ABC12 NUMBER(9,2) := XYZ * 131; V_CHR1 CHAR(89); V_CHR2 VARCHAR2(12) := "JANUARY"; TODAY DATE := SYSDATE; TRUEFALSE BOOLEAN;

Examples of constant declarations are given below :PI CONSTANT NUMBER(9,3) := 3.142; VAT CONSTANT NUMBER(4,2) := 17.5;

Examples of composite data types given below :V_NUM1 JD11.BOOK.COST%TYPE;

PL/SQL structure

Page 7: Ashish Raghute, IT Director, Fleetwood Enterprises Introduction to Procedural SQL (PL/SQL)

More hands-on:

CREATE TABLE T1(     e INT,     f INT );

DELETE FROM T1;

INSERT INTO T1 VALUES(1, 3);

INSERT INTO T1 VALUES(2, 4);

/* Above is plain SQL; below is the PL/SQL program. */

DECLARE     a NUMBER;     b NUMBER; BEGIN     SELECT e,f INTO a,b FROM T1 WHERE e>1;     INSERT INTO T1 VALUES(b,a); END; . Run;

PL/SQL structure

Page 8: Ashish Raghute, IT Director, Fleetwood Enterprises Introduction to Procedural SQL (PL/SQL)

EXCEPTION handling –

DECLARE a NUMBER; b NUMBER;BEGIN SELECT e,f INTO a,b FROM T1 WHERE e>1; INSERT INTO T1 VALUES(b,a);EXCEPTION WHEN TOO_MANY_ROWS THEN dbms_output.put_line('Cant select multiple values!');END;/

Other common exceptions:

NO_DATA_FOUND, OTHERS

Suggested home work – Write a PL/SQL program that has multiple blocks with nested structure and multiple levels of exception handling.

PL/SQL structure

Page 9: Ashish Raghute, IT Director, Fleetwood Enterprises Introduction to Procedural SQL (PL/SQL)

Control Flow in PL/SQLDECLARE     a NUMBER;     b NUMBER; My_count number;BEGIN     SELECT count(*) INTO my_count FROM T1 WHERE e>1;     IF my_count=1 THEN         INSERT INTO T1 VALUES(b,a);     ELSE         INSERT INTO T1 VALUES(b+10,a+10);     END IF; END; .

LoopingDECLARE     i NUMBER := 1;BEGIN     LOOP         INSERT INTO T1 VALUES(i,i);         i := i+1;         EXIT WHEN i>100;     END LOOP; END;

Page 10: Ashish Raghute, IT Director, Fleetwood Enterprises Introduction to Procedural SQL (PL/SQL)

Control Flow in PL/SQLSome other useful loop-forming statements are:

•EXIT by itself is an unconditional loop break. Use it inside a conditional if you like. •A WHILE loop can be formed with     •WHILE <condition> LOOP        • <loop_body>    • END LOOP;

•A simple FOR loop can be formed with:     FOR <var> IN <start>..<finish> LOOP         <loop_body>     END LOOP;

Here, <var> can be any variable; it is local to the for-loop and need not be declared. Also, <start> and <finish> are constants.

Page 11: Ashish Raghute, IT Director, Fleetwood Enterprises Introduction to Procedural SQL (PL/SQL)

CursorsCursorsA cursor is a variable that can store multiple records. This record set can be the answer to some query. By fetching into the cursor each record, we can write a program to process the set, one record at a time.   DECLARE a T1.e%TYPE; b T1.f%TYPE; CURSOR T1Cursor IS SELECT e, f FROM T1 WHERE e < f for update;BEGIN OPEN T1Cursor; LOOP FETCH T1Cursor INTO a, b; EXIT WHEN T1Cursor%NOTFOUND; DELETE FROM T1 WHERE CURRENT OF T1Cursor;

INSERT INTO T1 VALUES(b, a);

END LOOP;

CLOSE T1Cursor;END;

Page 12: Ashish Raghute, IT Director, Fleetwood Enterprises Introduction to Procedural SQL (PL/SQL)

Procedures or stored proceduresCREATE TABLE T2 (

a INTEGER, b CHAR(10));

CREATE OR REPLACE PROCEDURE addtuple1(i IN NUMBER) ASBEGIN INSERT INTO T2 VALUES(i, 'xxx');END addtuple1;

Execute_procedure addtuple1(4);

CREATE OR REPLACE PROCEDURE addtuple2(     x T2.a%TYPE,     y T2.b%TYPE) AS BEGIN     INSERT INTO T2(a, b)     VALUES(x, y); END addtuple2;

Exec addtuple2(4,’test’);

Page 13: Ashish Raghute, IT Director, Fleetwood Enterprises Introduction to Procedural SQL (PL/SQL)

ProceduresCREATE TABLE T3 (     a INTEGER,     b INTEGER );

Variable b number;

CREATE PROCEDURE addtuple3(a NUMBER, b OUT NUMBER) AS BEGIN     b := 4;     INSERT INTO T3 VALUES(a, b); END;

/

Exec addtuple3(1,:b);

Print :b;

Page 14: Ashish Raghute, IT Director, Fleetwood Enterprises Introduction to Procedural SQL (PL/SQL)

FunctionsWe can also write functions instead of procedures. : CREATE FUNCTION <func_name>(<param_list>) RETURN <return_type> AS ...In the body of the function definition, "RETURN <expression>;" exits from the function and returns the value of <expression>.

To find out what procedures and functions you have created, use the following SQL query:

select object_type, object_name from user_objects where object_type = 'PROCEDURE'    or object_type = 'FUNCTION';

To drop a stored procedure/function: drop procedure <procedure_name>; drop function <function_name>;

A := my_function( your_function(C));

A := sin(tan(45));

Page 15: Ashish Raghute, IT Director, Fleetwood Enterprises Introduction to Procedural SQL (PL/SQL)

TriggersBasic Trigger Syntax

CREATE TABLE T4 (a INTEGER, b CHAR(10));

CREATE TABLE T5 (c CHAR(10), d INTEGER);

We create a trigger that may insert a row into T5 when a row is inserted into T4. Specifically, the trigger checks whether the new row has a first component 10 or less, and if so inserts the reverse tuple into T5:

CREATE TRIGGER trig1     AFTER INSERT ON T4     REFERENCING NEW AS newRow     FOR EACH ROW     WHEN (newRow.a <= 10)    BEGIN         INSERT INTO T5 VALUES(:newRow.b, :newRow.a);     END trig1;

Page 16: Ashish Raghute, IT Director, Fleetwood Enterprises Introduction to Procedural SQL (PL/SQL)

TriggersBelow is the syntax for creating a trigger in Oracle (which differs slightly from standard SQL syntax): CREATE [OR REPLACE] TRIGGER <trigger_name>     {BEFORE|AFTER} {INSERT|DELETE|UPDATE} ON <table_name>     [REFERENCING [NEW AS <new_row_name>] [OLD AS <old_row_name>]]     [FOR EACH ROW [WHEN (<trigger_condition>)]]     <trigger_body>

Some important points to note: •You may specify up to three triggering events using the keyword OR. Furthermore, UPDATE can be optionally followed by the keyword OF and a list of attribute(s) in <table_name>. If present, the OF clause defines the event to be only an update of the attribute(s) listed after OF.

Here are some examples:     ... INSERT ON R ...     ... INSERT OR DELETE OR UPDATE ON R ...     ... UPDATE OF A, B OR INSERT ON R ...•If FOR EACH ROW option is specified, the trigger is row-level; otherwise, the trigger is statement-level. •Only for row-level triggers: •The special variables NEW and OLD are available to refer to new and old tuples respectively.

Page 17: Ashish Raghute, IT Director, Fleetwood Enterprises Introduction to Procedural SQL (PL/SQL)

•Note: In the trigger body, NEW and OLD must be preceded by a colon (":"), but in the WHEN clause, they do not have a preceding colon! See example below.

•The REFERENCING clause can be used to assign aliases to the variables NEW and OLD.

•A trigger restriction can be specified in the WHEN clause, enclosed by parentheses. The trigger restriction is a SQL condition that must be satisfied in order for Oracle to fire the trigger. This condition cannot contain subqueries. Without the WHEN clause, the trigger is fired for each row.

•<trigger_body> is a PL/SQL block, rather than sequence of SQL statements. Oracle has placed certain restrictions on what you can do in <trigger_body>, in order to avoid situations where one trigger performs an action that triggers a second trigger, which then triggers a third, and so on, which could potentially create an infinite loop. The restrictions on <trigger_body> include:

•You cannot modify the same relation whose modification is the event triggering the trigger.

•You cannot modify a relation connected to the triggering relation by another constraint such as a foreign-key constraint.

Triggers

Page 18: Ashish Raghute, IT Director, Fleetwood Enterprises Introduction to Procedural SQL (PL/SQL)

TriggersViewing Defined Triggers

To view a list of all defined triggers,

use: select trigger_name from user_triggers;

For more details on a particular trigger:

select trigger_type, triggering_event, table_name, referencing_names, trigger_body from user_triggers where trigger_name = '<trigger_name>';

Page 19: Ashish Raghute, IT Director, Fleetwood Enterprises Introduction to Procedural SQL (PL/SQL)

About the Author

Ashish Raghute currently works as the IT Director at Fleetwood

Enterprises, Inc. , USA’s leader in recreational vehicle sales and a leading producer and retailer of manufactured housing. Prior to joining Fleetwood, Ashish was a Principal at IBM Business Consulting Services and Principal Consultant at PricewaterhouseCoopers Consulting. For more than 15 years, Ashish has guided companies of various sizes from dot net startups to Fortune 1000 to successfully realize their IT vision in the areas of CRM, ERP, Data Warehousing and E-Business. Ashish can be contacted via email at [email protected].