PL/SQL
PL/SQL
PL/SQL stands for Procedural Language extensions to the Structured Query Language (SQL).
PL/SQL can execute a number of queries in one block using single command.
One can create a PL/SQL unit such as procedures, functions, packages, triggers, and types, which are stored in the database for reuse by applications.
The PL/SQL engine resides in the Oracle engine.
The Oracle engine can process not only single SQL statement but also block of many statements.
Structure of PL/SQL Block:
DECLARE
declaration statements;
BEGIN
executable statements
EXCEPTIONS
exception handling statements
END;
/
Example:
SET SERVEROUTPUT ON;
SQL> DECLARE
var varchar2(40) := 'I love GeeksForGeeks' ;
BEGIN
dbms_output.put_line(var);
END;
/
PL/SQL Functions
PL/SQL functions are reusable blocks of code that can be used to perform specific tasks. They are similar to procedures but must always return a value.
Create Function in PL/SQ:
CREATE [OR REPLACE] FUNCTION function_name
(parameter_name type [, …])
— This statement is must for functions
RETURN return_datatype
{IS | AS}
BEGIN
— program code
[EXCEPTION
exception_section;
END [function_name];
Example:
CREATE OR REPLACE FUNCTION factorial(x NUMBER)
RETURN NUMBER
IS
f NUMBER;
BEGIN
IF x = 0 THEN
f := 1;
ELSE
f := x * factorial(x - 1);
END IF;
RETURN f;
END;
/
PL/SQL Views
PL/SQL views are saved queries that you can use to simplify complex data access. They act as virtual tables, presenting a subset of data from one or more tables.
Syntax
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE condition;
Example:
CREATE VIEW employee_view AS
SELECT employee_id, first_name, last_name, department
FROM
employee;
Run: select * from employee_view;
PL/SQL Triggers
PL/SQL triggers are block structures and predefined programs invoked automatically when some event occurs.
They are stored in the database and invoked repeatedly.
Syntax:
CREATE OR REPLACE TRIGGER trigger_name
BEFORE or AFTER or INSTEAD OF //trigger timings
INSERT or UPDATE or DELETE // Operation to be performed
of column_name
on Table_name
FOR EACH ROW
DECLARE
Declaration section
BEGIN
Execution section
EXCEPTION
Exception section
END;
/
Comments
Post a Comment