PL/SQL Introduction: Declare Data Type For Variables in PL/SQL
PL/SQL Introduction: Declare Data Type For Variables in PL/SQL
PL/SQL Introduction: Declare Data Type For Variables in PL/SQL
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.
% 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.
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
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;
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;
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 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.
% 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 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.
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.
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.
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;