0% found this document useful (0 votes)
77 views

PL/SQL: Procedural Language/Structured Query Language

PL/SQL is a procedural language that allows developers to perform operations on SQL and PL/SQL objects. It consists of a declaration section to define variables, an execution section containing executable statements, and an exception handling section. Variables must be declared with a name, data type, and width. Control statements like IF-THEN and loops allow conditional execution. Triggers are stored programs that execute automatically in response to events like DML statements and can be used to enforce business rules.

Uploaded by

Bhushan Narkhede
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views

PL/SQL: Procedural Language/Structured Query Language

PL/SQL is a procedural language that allows developers to perform operations on SQL and PL/SQL objects. It consists of a declaration section to define variables, an execution section containing executable statements, and an exception handling section. Variables must be declared with a name, data type, and width. Control statements like IF-THEN and loops allow conditional execution. Triggers are stored programs that execute automatically in response to events like DML statements and can be used to enforce business rules.

Uploaded by

Bhushan Narkhede
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

PL/SQL: Procedural Language/Structured Query language

1. Declaration Section: It contains PL/SQL identifiers such as variables, constants, cursors


 All local variables used in programs are defined and documented
2. Execution section: It contains executable statements that allow us to manipulate the variables that have
been declared in declaration section
a. Starts with keyword: BEGIN
b. Ends with keyword: END
c. This section supports all DML commands and SQL*plus built-in functions
d. It also supports DDL commands using native dynamic SQL or DBMS_SQL built in package
3. Exception handing section: It contains statements that are executed when runtime error occurs
4. Variables: Variable is nothing but the place holder in memory that holds the data
a. Every variable must have following
i. Valid name
ii. Data type
iii. Data width
5. Always use (SET SERVEROUTPUT ON) command before start programming – It allows the server to
communicate with you and enable the display of result on your default output device
a. SET SERVEROUPT ON;
b. DECLARE
i. V_TEST VARCHAR2(15);
6. We can check the values stored in variable by calling line procedure DBMS_OUTPUT Package
a. Declare
b. V_TEST VARCHAR2(15);
c. Begin
d. V_test := ‘Test’;
e. DBMS_OUPUT.PUT_LINE(V_TEST);
f. END
7. Now, we can fetch the data from table in variable
a. Set serveroutput on;
b. Decalre
c. V_Salary number (10);
d. Begin
e. Selecy salary into V_Salary from employees;
f. Where empid = 100;
g. DBMS_OUTPUT.PUT_LINE(V_Salary);
h. End/
8. Anchored Datatype – It is a datatype which you assign to variable based on the database objects. It will be
used when you don’t know the datatype and width of variable from the base table.
a. Syntax: Variable-name typed attribute % type
b. Set serveroutput on;
c. Declare
d. V_Fname students.first_name % type;
e. Begin
f. Select first_name into V_Fname from students
g. Where stu_id = 1;
h. DBMS_OUTPUT.PUT_LINE(V_Fname);
i. End/
9. Constants in PL/SQL:
a. Syntax: Constant-name CONSTANT datatype (10):= value;
b. We must have to initialize the constant in declaration section
c. Set serveroutput on;
d. Declare
v_pi CONSTANT number (10):= 300
e. Begin
f. Dbms_output.put_line(v_pi);
g. End
10. Defualt Keyword:
a. Set serveroutput on;
b. Declare
v_pi CONSTANT number (10) default 300
c. Begin
d. Dbms_output.put_line(v_pi);
e. End
11. Not Null:
a. Set serveroutput on;
b. Declare
v_pi CONSTANT number (10) not Null default 300
c. Begin
d. Dbms_output.put_line(v_pi);
e. End
12. BIND Varibale:
a. We can declare the Bind variable anywhere in the host environment. It will be refereed as host
variable
b. We have to use VARIABLE command to declare the bond variable
c. VARIABLE v_bind1 varchar2 (10);
d. Begin
e. :v_bind1 := ‘Test’
f. Dbms_output.put_line(:v_bind);
g. End
h. We have to use PRINT variable to display current value of bind variable
i. Print :v_bind1; or we can enter set Autoprint on; command for this

13. Control Statements in PL/SQL:


a. This statement allows us to control the execution flow of program depending on the given
conditions
b. We have two types of control statements:
i. IF Statements: IF THEN, IF THEN ELSE, IF THEN ELSE IF
ii. Case Statements: Simple Case, Searched case
14. IF THEN Statement:
a. It enables you to specify only single group of action to be taken
b. Syntax: IF condition THEN
Statement 1;

Statement n;
END IF;
c. Example
d. Set serveroutput on
e. Declare
f. V_num number :=9;
g. Begin
h. If V_num<10; Then
i. Dbms_output.put_line(‘Inside the IF’);
j. End If
k. dbms_output.put_line(‘Outside the IF’);
l. End /
15. IF THEN ELSE Statement:
a. Syntax: If condition then
b. Statement 1
c. Else
d. Statement 2
e. End If
f. Statement 3;
g. Example
h. Set serveroutput on;
i. Declare
j. v_num number = &enter_Number;
k. Begin
l. If mod (v_num,2) = 0 then
m. Dbsm_output.put_line(‘number is even’);
n. Else
o. Dbms_output.put_line(‘number is odd’);
p. End if
q. Dbms_output.put_line(‘completed’);
r. End/
16. IF THEN ELSIF Statement:
a. Syntax: If condition then
b. Statement 1
c. Elsif condition 2 then
d. Statement 2
e. Elsif condition 3 then
f. Statement 3
g. ---
h. Else
i. Statement n
j. End if
k. End

17. Iterative statements / Loops: we have to use the “EXIT” and “EXIR WHEN” keyword to terminate the loop
a. Simple Loop
b. While Loop
c. Numeric for Loop
d. Cursor for Loop

18. Simple Loop


a. Syntax: Loop
b. Statement 1;
c. Statement 2;
d. Statement 3;
e. End Loop;
f. Example
g. Set serveroutput on;
h. Declare
i. v_counter number := 0
j. v_result number;
k. begin
l. loop
m. v_counter := v_couunter + 1;
n. v_result := 19 * v_counter;
o. dbms_output.put_line (‘19’ || ‘x’ ||v_counter|| ‘=’ || v_result);
p. exit when v_counter >= 10;
q. End Loop;
r. End:
s. /

19. While condition Loop


a. Syntax: While Condition Loop
b. Statement 1;
c. Statement 2;
d. Statement 3;
e. End Loop
f. Example:

20. Numeric for Loop:


a. Syntax: For loop_counter IN [reverse] lower_limit..upper_limit
b. Statement 1
c. Statement 2
d. ---
e. Statement 3
f. End Loop
g. Example:
i. Set serveroutput on;
ii. Begin
iii. For v_counter IN 1..10 Loop
iv. Dbms_output.put_line(v_counter);
v. End loop
vi. End
h. If we want to print this numbers in reverse order, we just have to use “REVERSE” keyword
i. Set serveroutput on;
ii. Begin
iii. For v_counter IN REVERSE 1..10 Loop
iv. Dbms_output.put_line(v_counter);
v. End loop
vi. End
21. Triggers:
a. Triggers are a named PL/SQL block which are stored in the database
b. Triggers are specialized stored programs which execute implicitly when triggering event occurs
c. This can be executed implicitly based on following events:
i. DML Statements
ii. DDL Statement
iii. System Event
iv. User Event
d. Types of Triggers:
i. DML Triggers – Depends on update, insert, delete statements (fired before or after
statements)
ii. DDL Triggers – Depends on Create, Alter (Use: we can monitor the behavior and force rules
on DDL statements)
iii. System/Database Triggers: Depends on log on of log off of database
iv. Instead of Triggers:
v. Compound Triggers: It can be used to audit, check and replace the values when need to take
action at statement and row level event
vi. Syntax:
1. CREATE [OR REPLACE] TRIGGER TRIGGER_NAME
2. {BEFORE/AFTER} TRIGGERING_EVENT ON TABLE_NAME
3. [FOR EACH ROW] [FOLLOW ANOTHER_TRIGGER_NAME]
4. [ENABLE/DISABLE] [WHEN CONDITION]
5. DECALRE
6. DECLARATION STATEMENT
7. BEGIN
8. EXECUTABLE STATEMENT
9. END;
vii. Uses:
1. Enforce business rules
2. Gain strong control over the security
3. Collect statistical information
4. Automatically generate values
5. Prevent invalid transaction
viii. DML Trigger:
1. set serveroutput on;
2. create or replace trigger tl_hr
3. before insert or update or delete on tl_hr
4. for each row
5. enable
6. declare
7. v_user varchar2 (10);
8. Begin
9. Select user into v_user from dual;
10. If inserting then
11. Dbms_output.put_line (‘one row inserted by’ || v_user);
12. Elsif deleting then
13. Dbms_output.put_line (‘one row deleted by’ || v_user);
14. Elsif updating
15. Dbms_output.put_line (‘one row updated by’ || v_user);
16. End if;
17. End;
ix. Synchronized backup copy of table:
x. DDL Trigger:
CREATE TABLE schema_audit(
ddl_date DATE,
ddl_user VARCHAR2(15),
object_created VARCHAR2(15),
object_name VARCHAR2(15),
ddl_operation VARCHAR2(15)
);
CREATE OR REPLACE TRIGGER hr_audit_tr
AFTER DDL ON SCHEMA
BEGIN
INSERT INTO schema_audit VALUES (
sysdate, sys_context('USERENV','CURRENT_USER'),
ora_dict_obj_type,
ora_dict_obj_name,
ora_sysevent);
END;
/
xi. Database/ System event Triggers:
Syntax: CREATE OR REPLACE TRIGGER trigger_name
BEFORE | AFTER database_event ON database/schema
BEGIN
PL/SQL Code
END;
/

CREATE TABLE hr_evnt_audit


(
event_type VARCHAR2(30),
logon_date DATE,
logon_time VARCHAR2(15),
logof_date DATE,
logof_time VARCHAR2(15)
);
CREATE OR REPLACE TRIGGER hr_lgon_audit
AFTER LOGON ON SCHEMA
BEGIN
INSERT INTO hr_evnt_audit VALUES(
ora_sysevent,
sysdate,
TO_CHAR(sysdate, 'hh24:mi:ss'),
NULL,
NULL
);
COMMIT;
END;
/

xii. Instead of Insert Trigger:


1. Using this trigger, we can control default behavior of Insert, Update, Delete and
Merge operations on “Views”
CREATE [OR REPLACE] TRIGGER trigger_name
INSTEAD OF operation
ON view_name
FOR EACH ROW
BEGIN
---Your SQL Code—
END;
CREATE TABLE trainer
(
full_name VARCHAR2(20)
);
CREATE TABLE subject
(
subject_name VARCHAR2(15)
);
INSERT INTO trainer VALUES ('Manish Sharma');
INSERT INTO subject VALUES ('Oracle');
CREATE VIEW vw_rebellionrider AS
SELECT full_name, subject_name FROM trainer, subject;
CREATE OR REPLACE TRIGGER tr_Io_Insert
INSTEAD OF INSERT ON vw_rebellionrider
FOR EACH ROW
BEGIN
INSERT INTO trainer (full_name) VALUES (:new.full_name);
INSERT INTO subject (subject_name) VALUES (:new.subject_name);
END

xiii. Cursor:
1. Cursor is a pointer to a memory area called context area
2. It is used to hold the information about the processing of SELECT statement or DML
statement
3. Context Area: It is used to hold the information of following
a. Rows returned by query
b. Number of rows processed by query
c. A pointer to the parsed query in the shared pool
4. Types of Cursors:
a. Implicit Cursor
b. Explicit Cursor
5. Implicit Cursor:
a. Automatically created by Oracle Server
b. User cannot control the behavior of cursor
c. Oracle server creates an implicit cursor for any PL/SQL block which executes
an SQL statements
6. Explicit Cursor:
a. It is user defined cursors
b. User can create cursor for any statement which returns more than one row
of data
c. User has full control on Explicit cursor
d. To create explicit cursor, we need to follow four (4) steps:
i. Declare
ii. Open
iii. Fetch
iv. Close
e. Syntax: CURSOR cursor_name IS select_statement (In Declaration block)
i. Open cursor_name; (In Execution block)
ii. FETCH cursor_name INTO PL/SQL variable; (To fetch the data from
cursor)
iii. Close cursor_name; (closing the cursor)
SET SERVEROUTPUT ON;
DECLARE
v_name VARCHAR2(30);
--Declare Cursor
CURSOR cur_RebellionRider IS
SELECT first_name FROM EMPLOYEES
WHERE employee_id < 105;
BEGIN
OPEN cur_RebellionRider;
LOOP
FETCH cur_RebellionRider INTO v_name;
DBMS_OUTPUT.PUT_LINE (v_name);
EXIT WHEN cur_RebellionRider%NOTFOUND;
END LOOP;--Simple Loop End
CLOSE cur_RebellionRider;
END;
/
xiv. Cursor Parameter
CURSOR cur _ name (parameter list) IS SELECT statement;
OPEN cur _ name (argument list)
ET SERVEROUTPUT ON;
DECLARE
v_name VARCHAR2 (30);
--Declare Cursor
CURSOR p_cur_RebellionRider (var_e_id VARCHAR2) IS
SELECT first_name FROM EMPLOYEES
WHERE employee_id < var_e_id;
BEGIN
OPEN p_cur_RebellionRider (105);
LOOP
FETCH p_cur_RebellionRider INTO v_name;
EXIT WHEN p_cur_RebellionRider%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(v_name );
END LOOP;
CLOSE p_cur_RebellionRider;
END;
22. Stored Procedures:
a. Stored Procedures is a self-contained sub program that is meant to do some specific task
b. Procedures are named PL/SQL blocks thus they can be reused because they are stored in the
database as database object
CREATE OR REPLACE PROCEDURE pr_RebellionRider IS
var_name VARCHAR2 (30):= 'Manish';
var_web VARCHAR2 (30) := 'RebellionRider.com';
BEGIN
DBMS_OUTPUT.PUT_LINE('Whats Up Internet? I am '||var_name||'
from '||var_web);
END Pr_RebellionRider;
CREATE OR REPLACE PROCEDURE emp_sal( dep_id NUMBER, sal_raise
NUMBER)
IS
BEGIN
UPDATE emp SET salary = salary * sal_raise WHERE department_id
= dep_id;
END;
c. We have to use “Execute” commands to run the stored procedures
23. Calling notations:
a. Positional notation – we have to specify value for each formal parameter in seq manner
b. Named notation -
c. Mixed calling notation
24. PL/SQL Packages:
a. Packages are stored libraries in the database which allow us to group PL/SQL objects under one
name
b. Packages are logical groups of related PL/SQL objects
c. Permanently stored in the database schema
d. Packages includes:
i. Stored Procedures
ii. PL/SQL functions
iii. Database cursors
iv. Type declaration
v. Variables
e. Package Architecture
i. Package specification
ii. Package Body
f. Package Specification: Also known as package header (Whatever we declare in this section are
publicly available and can be referenced outside of package)
i. Syntax:
1. CREATE OR REPLACE PACKAGE PKG_NAME IS
DECLARATION OF ALL THE PACKAGE ELEMENT;
END [PKG_NAME];
g. Package Body: We provide actual structure of all the package elements
i. It contains both declaration of variables as well as definition of package element
ii. Syntax:
1. CREATE OR REPLACE PACKAGE BODY PKG_NAME IS
VARIABLE DECLARATION;
TYPE DECLARATION;
BEGIN
IMPLEMENTATION OF PACKAGE ELEMENTS
END [PKG_NAME];
h. Example:
i. -----PACKAGE SPECIFICATION----
CREATE OR REPLACE PACKAGE pkg_RebellionRider IS
FUNCTION prnt_strng RETURN VARCHAR2;
PROCEDURE proc_superhero(f_name VARCHAR2, l_name VARCHAR2);
END pkg_RebellionRider;
ii. -----PACKAGE BODY-----------------
CREATE OR REPLACE PACKAGE BODY pkg_RebellionRider IS
--Function Implimentation
FUNCTION prnt_strng RETURN VARCHAR2 IS
BEGIN
RETURN 'RebellionRider.com';
END prnt_strng;

--Procedure Implimentation
PROCEDURE proc_superhero(f_name VARCHAR2, l_name VARCHAR2) IS
BEGIN
INSERT INTO new_superheroes (f_name, l_name) VALUES(f_name,
l_name);
END;

END pkg_rrdr;
BEGIN
DBMS_OUTPUT.PUT_LINE (PKG_RebellionRider.PRNT_STRNG);
END;
25. PL/SQL Functions:
a. Function is a self-contained sub-program meant to do some specific well-defined task
b. Functions can be stored into the database as database objects
CREATE [OR REPLACE] FUNCTION function_name
(Parameter 1, Parameter 2…)
RETURN datatype
IS
Declare variable, constant etc.
BEGIN
Executable Statements
Return (Return Value);
END;
c. With PL/SQL functions it is mandatory to specify a return value. To specify the return value, we use
“RETURN” keyword followed by the datatype in header of function.
d. Example:
CREATE OR REPLACE FUNCTION circle_area (radius NUMBER)
RETURN NUMBER IS
--Declare a constant and a variable
Pi CONSTANT NUMBER(7,2) := 3.141;
Area NUMBER(7,2);
BEGIN
--Area of Circle pi*r*r;
area := pi * (radius * radius);
RETURN area;
END;
26. Exceptional Handling:
SET SERVEROUTPUT ON;
DECLARE
var_dividend NUMBER := 24;
var_divisor NUMBER := 0;
var_result NUMBER;
ex_DivZero EXCEPTION;
BEGIN
IF var_divisor = 0 THEN
RAISE ex_DivZero;
END IF;
var_result := var_dividend/var_divisor;
DBMS_OUTPUT.PUT_LINE('Result = ' ||var_result);
EXCEPTION WHEN ex_DivZero THEN
DBMS_OUTPUT.PUT_LINE('Error Error - Your Divisor is Zero');
END;

i. Record Data types:


1. Records are the composite data structures made of different components called
fields
2. Record is a group of related data items stored in fields, each with its own name and
datatypes
3. Types:
a. Table based records
b. Cursor based records
c. User defined records
27. Views:

You might also like