Sunteți pe pagina 1din 15

PL/SQL Introduction

PL/SQL (Procedural Language / Structured Query Language) is the procedural extension of SQL language. PL/SQL is a programming language that provides accessing data from a relational database-oriented objects and enables grouping of a multitude of commands into a single block of data handling. PL/SQL is a language with block structure. It enable programmers to codify procedures, functions, and anonymous blocks that combine SQL statements with procedural instructions. Procedures, functions and cursors that form a logical drive can be grouped and stored together in packages. These packages may be provide parameters, which allows the procedures and functions to receive and return values.

PL/SQL Advantages
Integration with Oracle Server Supports the basic SQL commands Defining and managing blocks of instructions Management of variables, constants and cursors Allow implementation and use of triggers Detection and management execution errors, exceptions

PL/SQL Blocks
PL/SQL is a language focused on blocks, with procedural and processing characteristics of error handling. These blocks are composed of procedures, functions, and anonymous blocks which are grouped together in logical point of view. A PL/SQL block is composed of three parts: Declaration - all block objects must be declared Execution the objects are defined for the data processing Exceptions here are located the error handling routines DECLARE Declare Variables BEGIN Execution Programs EXCEPTION Errors handling END;

PL/SQL Variables
Variables can be any SQL data type such as CHAR, DATE, or NUMBER, or a type of date PL/SQL such as BOOLEAN or PLS_INTEGER.

DECLARE DATA TYPE FOR VARIABLES IN PL/SQL


You can use the special %words% ROWTYPE TYPE or to declare variables that keeps the columns of tables or records of the tables.

% TYPE attribute provides the ability to set the type of the date of a variable as being the same with the type of the date of a column in a table. Example: v_last_name Dormer. last_name% TYPE; % ROWTYPE attribute offers a type of record that represents a row in a database table. Registration can store all row in the table.

1. Declaring Variables in PL/SQL


DECLARE part_no NUMBER (6); part_name VARCHAR2 (20); in_stock BOOLEAN; part_price NUMBER (6.2); part_desc VARCHAR2 (50);

2. Assigning variables using the := operator


DECLARE hours_worked NUMBER: = 40; hourly_salary NUMBER: = 22.50; bonus NUMBER: = 150; country VARCHAR2 (128); counter NUMBER: = 0; done BOOLEAN; emp_rec1 employees% ROWTYPE; emp_rec2 employees% ROWTYPE; BEGIN wages: = (hours_worked * hourly_salary) + bonus; country: = ' Italy '; country: = UPPER (' Spain '); done: = (counter > 100); emp_rec1.: first_name = ' John '; emp_rec1. last_name: = ' Davis '; emp_rec1: = emp_rec2; END;

3. Assigning values to a variable using Select Into


DECLARE bonus NUMBER (8,2); emp_id NUMBER (6): = 100; BEGIN SELECT salary * 0.10 INTO bonus FROM employees WHERE employee_id = emp_id; END;

4. Assigning Value to a Variable as a parameter of a subroutine


DECLARE new_sal NUMBER (8,2); emp_id NUMBER (6): = 126; PROCEDURE adjust_salary (emp_id NUMBER, sal IN OUT NUMBER) IS emp_job VARCHAR2 (10); avg_sal NUMBER (8,2); BEGIN SELECT job_id INTO emp_job FROM employees WHERE emp_id = employee_id; SELECT AVG (salary) INTO avg_sal FROM employees WHERE job_id = emp_job; DBMS_OUTPUT.PUT_LINE (' The average salary for ' emp_job || || ' employees: ' || TO_CHAR (avg_sal)); sal: = (sal + avg_sal)/2; --adjust sal value which is returned END; BEGIN SELECT AVG (salary) INTO new_sal FROM employees; DBMS_OUTPUT.PUT_LINE (' The average salary for all employees: ' || TO_CHAR (new_sal)); adjust_salary (emp_id, new_sal); --assigns a new value to new_sal DBMS_OUTPUT.PUT_LINE (' The adjusted salary for employee ' || TO_CHAR (emp_id) || ' is ' || TO_CHAR (new_sal)); sal has new value END;

PL/SQL Control structures: PL/SQL If-Then-Else Statement


Oracle PL / SQL provides the ability to formulate conditions and depending on the veracity of these conditions to execute a block or not to execute.

IF - THEN
If a = 5 Then ... End If;

IF - THEN - ELSE
If b = 10 Then ... Else ... End If;

IF - THEN - ELSIF
If c = 15 Then ... ElsIf c = 16 Then ... Else

... End If;

IF
IF has 3 shapes: IF-THEN, IF-THEN-ELSE and IF-THEN-ELSIF.

DECLARE c varchar2(30); BEGIN IF c IS NULL THEN DBMS_OUTPUT.PUT_LINE('Value of c is null.'); ELSE DBMS_OUTPUT.PUT_LINE('Value of c is not null.'); END IF; END;

Example: DECLARE sales NUMBER (8.2): = 12100; quota NUMBER (8.2): = 10,000; bonus NUMBER (6.2); emp_id NUMBER (6): = 120; BEGIN IF sales > (quota + 200) THEN bonus: = (sales quota)/4; ELSE bonus: = 50; END IF; UPDATE employees SET salary = salary + bonus WHERE employee_id = emp_id; END; Example: DECLARE jobid Dormer. job_id% TYPE; empid Dormer. employee_id% TYPE: = 115; sal_raise NUMBER (3,2); BEGIN SELECT job_id INTO jobid from employees WHERE empid employee_id =; IF jobid = ' PU_CLERK ' THEN sal_raise: =. 09; ELSIF jobid = ' SH_CLERK ' THEN sal_raise: =. 08; ELSIF jobid = ' ST_CLERK ' THEN sal_raise: =. 07; ELSE sal_raise: = 0;

END IF; END; Example: DECLARE sales NUMBER (8.2): = 20000; bonus NUMBER (6.2); emp_id NUMBER (6): = 120; BEGIN IF sales > 50,000 THEN bonus: = 1500; ELSIF sales > 35,000 THEN bonus: = 500; ELSE bonus: = 100; END IF; UPDATE employees SET salary = salary + bonus WHERE employee_id = emp_id; END;

PL/SQL Case Statement


PL/SQL Case Statement - This instruction allows to set up structures like IF conditional test .. ELSE .. END IF the difference it can be used in SQL queries

PL/SQL SIMPLE CASE STATEMENT, CASE - WHEN


[label] CASE WHEN operator {content_operator THEN {statement;} ... ...} [ELSE {statement;}...] END CASE [label]; For the simple CASE, each WHEN keyword verifies the equality operator and content_operator. If so, the statement following the THEN keyword is executed, then the CASE structure is exited and program execution is resumed after the keyword END CASE; Example: DECLARE value CHAR(1); BEGIN value := 'B'; CASE value WHEN 'A' THEN DBMS_OUTPUT.PUT_LINE('1'); WHEN 'B' THEN DBMS_OUTPUT.PUT_LINE('2'); WHEN 'C' THEN DBMS_OUTPUT.PUT_LINE('3'); WHEN 'D' THEN DBMS_OUTPUT.PUT_LINE('4'); WHEN 'F' THEN DBMS_OUTPUT.PUT_LINE('5'); ELSE DBMS_OUTPUT.PUT_LINE('No such value'); END CASE; END;

PL/SQL SEARCHED CASE STATEMENT


[label] CASE WHEN {Boolean_Expression THEN {statement;} ... ...} [ELSE {statement;}...] END CASE [label]; operator can be any PL / SQL with the exception of the following: BLOB, BFILE, Object Type, Registration, Collection (NESTED TABLE, INDEX-BY TABLE, VARRAY) Example: Declare i pls_integer := 0 ; Begin Loop i := i + 1 ; CASE WHEN i between 1 and 4 Then dbms_output.put_line( To_char( i ) || ' -> 1-4' ) ; ELSE dbms_output.put_line( To_char( i ) || ' >= 5' ) ; END CASE ; exit when i = 5 ; End loop ; End ;

CASE
Example DECLARE degrees CHAR (1); BEGIN degrees: = ' B '; CASE degrees WHEN ' A ' THEN DBMS_OUTPUT.PUT_LINE (' Excellent '); WHEN ' B ' THEN DBMS_OUTPUT.PUT_LINE (' Very Good '); WHEN ' C ' THEN DBMS_OUTPUT.PUT_LINE (' Good '); WHEN ' D ' THEN DBMS_OUTPUT.PUT_LINE (' Fair '); WHEN ' F ' THEN DBMS_OUTPUT.PUT_LINE (' Poor '); ELSE DBMS_OUTPUT.PUT_LINE (' No such degrees '); END CASE; END; Example: DECLARE degrees CHAR (1); BEGIN degrees: = ' B '; CASE WHEN degrees = ' A ' THEN DBMS_OUTPUT.PUT_LINE (' Excellent '); WHEN degree = ' B ' THEN DBMS_OUTPUT.PUT_LINE (' Very Good '); WHEN degree = ' C ' THEN DBMS_OUTPUT.PUT_LINE (' Good ');

WHEN degree = ' D ' THEN DBMS_OUTPUT.PUT_LINE (' Fair '); WHEN degree = ' F ' THEN DBMS_OUTPUT.PUT_LINE (' Poor '); ELSE DBMS_OUTPUT.PUT_LINE (' No such degrees '); END CASE; END;

LOOP
There are 3 forms for LOOP: LOOP, WHILE-LOOP, FOR-LOOP Example DECLARE credit_rating NUMBER: = 0; BEGIN LOOP credit_rating: = credit_rating + 1; IF credit_rating > 3 THEN EXIT; END IF; END LOOP; IF credit_rating > 3 THEN RETURN; END IF; DBMS_OUTPUT.PUT_LINE (' Credit ratings: ' || TO_CHAR (credit_rating)); END;

EXIT
IF count > 100 THEN EXIT; ENDIF;

EXIT-WHEN
EXIT WHEN count > 100;

PL/SQL While Loop


The Loop statement WHILE-LOOP run so long as the condition is true. Syntax: WHILE condition LOOP sequence_of_statements LOOP END; This is equivalent to: LOOP sequence_of_statements EXIT WHEN boolean_expression; END LOOP; Example:

Declare v_count number(2) := 1; Begin While v_count <= 50 Loop Select name into book.name From visits v_count := v_count + 1; End Loop; End;

PL/SQL For Loop


FOR cycles add instructions at the beginning of cycle control, which will determine the number of iterations to be performed. Syntax: var FOR IN [REVERSE] var_min .. var_max Example 1: FOR i IN 1 .. 2000 LOOP INSEERT no_rows INTO VALUES (i); preserve_i: = i; ... END LOOP; Where 'var' is the name of an entire variables whose values will be set higher/low automatically each iteration of the cycle. This variable is created by cycle and cannot be written by any statement in the cycle. Lifetime ends at the end of the cycle. 'var_min' and 'var_max' are entire phrases, which determine the values that you will get the variable control. By default, the control variable is initialized with a value of is small, and with + 1 increased at each iteration the value high till is reached. Example 2: BEGIN FOR v_count IN 1..10 LOOP IF v_count NOT IN (10,12) THEN INSERT INTO messages (col1) VALUES (v_count); END IF; END LOOP; COMMIT; END;

PL/SQL Cursors
PL/SQL uses implicit and explicit cursors. PL/SQL declare a implicit cursor for each operation to data manipulation in SQL, including queries that returns a single registration. If you want precise control over the interogations, you can declare a explicit cursor; You can define a explicit cursor for the interogations which returns more than one registration.

1. IMPLICIT CURSORS
The default cursors are managed automatically by the PL/SQL, so you don't have written any code for handling them. Can you account for the execution of a implicit cursor through the attributes of the cursor.

The attributes of the default cursors


The attributes of the default cursors can return information about DML and DDL execution commands such as INSERT, UPDATE, DELETE, SELECT INTO, COMMIT or ROLLBACK. The attributes are: % FOUND cursor, % ISOPEN, % NOTFOUND and % ROWCOUNT.

% FOUND
Until SQL data manipulation is executed, the attribute % FOUND is NULL. So, % FOUND is TRUE if the command type of INSERT, UPDATE, or DELETE affects one or more records from the database or SELECT INTO returns one or more recordings. Example: use of attribute SQL % FOUND CREATE TABLE dept_temp AS SELECT * FROM departments; DECLARE dept_no NUMBER (4): = 270; BEGIN DELETE FROM dept_temp WHERE department_id = dept_no; IF FOUND THEN SQL%--if the deletion was successful INSERT INTO dept_temp VALUES (270, ' Personnel ', 200, 1700); END IF; END;

% ISOPEN
Oracle closes the cursor automatically after execution of commands. As a result,% ISOPEN becomes FALSE.

% NOTFOUND
% NOTFOUND is the opposite attribute of % FOUND. % NOTFOUND is TRUE if the INSERT, UPDATE, or DELETE your registration does not affect any of the database or SELECT INTO does not return any registration. Otherwise it is FALSE.

% ROWCOUNT
% ROWCOUNT returns the number of records affected by one of the commands that INSERT, UPDATE, or DELETE, or the number of records affected by the SELECT INTO. % ROWCOUNT is 0 if the command INSERT, UPDATE, or DELETE does not affect any inregistrae, or SELECT INTO does not return any registration. Example: Using SQL% ROWCOUNT CREATE TABLE employees_temp AS SELECT * FROM employees; DECLARE mgr_no NUMBER (6): = 122; BEGIN DELETE FROM employees_temp WHERE manager_id = mgr_no; DBMS_OUTPUT.PUT_LINE (' Number of employees deleted: ' || TO_CHAR (SQL% ROWCOUNT)); END;

2. EXPLICIT CURSORS
When you need precise control over the outcome of the interogations, must be declared a explicit cursor in PL/SQL. Three commands are used to control a cursor: OPEN, FETCH and CLOSE. First time the cursor must must be opened through the OPEN command. Then you can run FETCH repeated until all records have been read or you can use BULK COLLECT clause to read all recording only once. For disable/close a cursor uses the CLOSE command.

% ROWTYPE
DECLARE v_jobid employees.job_id%TYPE; v_lastname employees.last_name%TYPE; CURSOR SELECT last_name, c1 IS the job_id FROM employees WHERE REGEXP_LIKE (job_id, 'CLERK'); v_employees employees%ROWTYPE; CURSOR c2 is SELECT * FROM employees WHERE REGEXP_LIKE (job_id, ' [ACADFIMKSA] _ M [ANGR] '); BEGIN OPEN c1; --opening the cursor LOOP FETCH c1 INTO v_lastname, v_jobid; EXIT WHEN c1%NOTFOUND; DBMS_OUTPUT.PUT_LINE (RPAD (v_lastname, 25, ' ') || v_jobid); END LOOP; CLOSE c1; DBMS_OUTPUT.PUT_LINE( '---' ); OPEN c2; LOOP FETCH c2 INTO v_employees; EXIT WHEN c2% NOTFOUND;

DBMS_OUTPUT.PUT_LINE (RPAD (v_employees., 25, ' last_name ') || v_employees. job_id); END LOOP; CLOSE c2; END;

PL/SQL Stored Procedures


Stored procedures are called blocks that allow grouping and organization of SQL commands and PL/SQL. Both source code and the executable are stored in the database. By storing it in the database, the code is situated in accessible and centralized location. Because the executable code is located in the database, invoke stored procedures is more efficient.

How to create Stored Procedures ?


Stored procedures can be created with the CREATE PROCEDURE command, which declare a list of parameters and actions that are build a PL/SQL block. Parameters are used to transfer data between values and call the procedure. Parameters can have one of 3 ways: IN, OUT and OUT. - IN is sending a constant value of the procedure - OUT sends a value from the procedure a variable - IN OUT sending a value to the procedure and a value different from the procedure to a variable, using the same parameter. Exemple Stored Procedure: CREATE OR REPLACE PROCEDURE raise_salary (p_id IN employees.employee_id%Type, p_percent IN NUMBER) IS BEGIN UPDATE employees SET salary= salary*(1+p_percent/100) WHERE employee_id = p_id; END raise_salary; Begin raise_salary(200,10); End;

PL/SQL Functions
A function is a PL/SQL block with names that accept parameters, can be called and can return a value. In general, it uses a function to calculate a value.

How to create a Function ?


The function will be created using the CREATE FUNCTION command which declare a list of parameters and defines actions to be performed by standard PL/SQL block. Functions and procedures are similar structures. A function may return a value, while a procedure may return zero or more values through parameters. As a procedure, a function has a header, a section of statements, a section of code

executable and a section for managing exceptions. A function must have "return" clause in header and at least a "return" clause in section of the executable code. Exemple Create Function: CREATE OR REPLACE FUNCTION Get_Salary (p_id employees.employee_id%Type) RETURN NUMBER IS v_sal employees.salary%TYPE :=0; BEGIN SELECT salary INTO v_sal FROM employees WHERE employee_id = p_id; RETURN v_sal; END Get_Salary; Begin dbms_output.put_line(Get_Salary(200)); End;

PL/SQL Packages
A package, as it says the name, procedural objects grouped by type of procedures, functions, variables, exceptions, cursors and ranges. Each package consists of two parts: - Specification of the package is the interface for the application. Here we can declare public types, variables, constants, and exceptions, cursors and subprograme. - The body of the package defines its own subroutine. The body of the packet can define also PL/SQL constructions, such as variables, constants, and exceptions and cursors.

Exemple of PL/SQL Packages:


CREATE PACKAGE Give_Data AS TYPE TimeRec IS RECORD ( minutes SMALLINT, hours SMALLINT); TYPE GiveRec IS RECORD ( category VARCHAR2(10), account INT, amount REAL, time_of TimeRec); minimum_balance CONSTANT REAL := 50.00; number_processed INT; insufficient_funds EXCEPTION; END Give_Data;

PL/SQL Exception Handling


Exception Handling or management of errors in PL/SQL refers to the concept of exception. The exception is a private event (error or warning message) generated by the server or application that needs special treatment. Exceptions may be defined, enabled, treated at the level of each block in the program. Execution of a block ends when an exception occurs, but may run subsequent actions, its appearance in a special section for handling exceptions. In PL/SQL there are two types of exceptions: -internal exceptions that occur when a PL/SQL block does not comply with a rule of the server -external user-defined exceptions, which are declared in section declarativa block, subroutine or package and which are activated explicitly in the executabila block, PL/SQL. EXCEPTION WHEN No_Data_Found THEN statement1; WHEN Too_Many_Rows THEN statement2; WHEN Others THEN statement3; For the processing of internal exceptions we can use WHEN OTHERS exceptions or pragma EXCEPTION_INIT. A pragma is a compilation directive. In PL/SQL pragma EXCEPTION_INIT merge a exception_name with a number of Oracle error, interference, allows the reference to the exception by name. DECLARE exception_name EXCEPTION; PRAGMA EXCEPTION_INIT (exception_name,-50); BEGIN --plsql code; EXCEPTION WHEN exception_name THEN --error processing END;

ACCESS_INTO_NULL CASE_NOT_FOUND COLLECTION_IS_NULL CURSOR_ALREADY_OPEN DUP_VAL_ON_INDEX INVALID_CURSOR INVALID_NUMBER LOGIN_DENIED NO_DATA_FOUND NOT_LOGGED_ON PROGRAM_ERROR ROWTYPE_MISMATCH

ORA-06530 ORA-06592 ORA-06531 ORA-06511 ORA-00001 ORA-01001 ORA-01722 ORA-01017 ORA-01403 ORA-01012 ORA-06501 ORA-06504

SELF_IS_NULL ORA-30625 STORAGE_ERROR ORA-06500 SUBSCRIPT_BEYOND_COUNT ORA-06533 SUBSCRIPT_OUTSIDE_LIMIT ORA-06532 SYS_INVALID_ROWID ORA-01410 TIMEOUT_ON_RESOURCE ORA-00051 TOO_MANY_ROWS ORA-01422 VALUE_ERROR ORA-06502 ZERO_DIVIDE ORA-01476

PL/SQL RAISE_APPLICATION_ERROR
The call is accomplished only in a subroutine that is cached. CREATE PROCEDURE raise_salary (emp_id NUMBER, rate NUMBER) AS v_salary NUMBER; BEGIN SELECT salary INTO v_salary FROM emp WHERE empno = emp_id; IF v_salary IS NULL THEN RAISE_APPLICATION_ERROR (-20100, ' Missing salary); ELSE UPDATE emp SET salary = v_salary + rate WHERE empno = emp_id; END IF; END raise_salary;

PL/SQL Triggers
A trigger is a PL/SQL block which will run automatically whenever an event occurs. PL/SQL block may be associated with a table, a view or to a database. A trigger is a procedure to be run automatically when it is launched on the table associated with a command to the insert, update, or delete. Triggers can contain instructions to PL/SQL and SQL STATEMENTS that are executed as a block and in turn can trigger the execution of other procedures and other triggers. The trigger can be invoked either before or after the execution of the order insert, update, or delete.

Triggers can be:


- Trigger for the application: this type of trigger is run when an event occurs in an application. -Trigger for database (DML): this type of trigger is run whenever an event occurs in a database. CREATE OR REPLACE TRIGGER trigger_name {BEFORE | AFTER | INSTEAD OF} {INSERT | UPDATE | DELETE} [OF column_name] ON table_name [REFERENCING OLD AS old NEW AS new] [FOR EACH ROW]

WHEN (condition) BEGIN --- pl/sql statements END; Triggers at the database level may be of two kinds: -at the level of instruction (statement level trigger) -line level (row level trigger) -- before statement trigger CREATE OR REPLACE TRIGGER before_ trigger BEFORE INSERT ON frame BEGIN DBMS_OUTPUT.PUT_LINE('Before Insert Statement Level'); END; -- before row trigger CREATE OR REPLACE TRIGGER before_row_trigger BEFORE INSERT ON frame FOR EACH ROW BEGIN DBMS_OUTPUT.PUT_LINE('Before Insert Row Level'); END;

S-ar putea să vă placă și