SlideShare a Scribd company logo
1 of 31
๏ฝ Procedural Language โ€“ SQL
๏ฝ An extension to SQL with design features of
programming languages (procedural and object
oriented)
๏ฝ PL/SQL and Java are both supported as internal
host languages within Oracle products.
๏ฝ Acts as host language for stored procedures
and triggers.
๏ฝ Provides the ability to add middle tier business
logic to client/server applications.
๏ฝ Provides Portability of code from one
environment to another
๏ฝ Improves performance of multi-query
transactions.
๏ฝ Provides error handling
DECLARE (optional)
- variable declarations
BEGIN (required)
- SQL statements
- PL/SQL statements or sub-blocks
EXCEPTION (optional)
- actions to perform when errors occur
END; (required)
Anonymous
DECLARE
BEGIN
-statements
EXCEPTION
END;
Procedure
PROCEDURE <name>
IS
BEGIN
-statements
EXCEPTION
END;
Function
FUNCTION <name>
RETURN <datatype>
IS
BEGIN
-statements
EXCEPTION
END;
๏ฝ Scalar (char, varchar2, number, date, etc)
๏ฝ Composite (%rowtype)
๏ฝ Reference (pointers)
๏ฝ LOB (large objects)
Note: Non PL/SQL variables include bind variables,
host (โ€œglobalโ€) variables, and parameters.
๏ฝ Two variables can have the same name if they are
in different blocks (bad idea)
๏ฝ The variable name should not be the same as any
table column names used in the block.
๏ฝ All variables must be declared before their use.
๏ฝ The assignment statement
: =
is not the same as the equality operator
=
๏ฝ All statements end with a ;
Variable g_inv_value number
DECLARE
v_price number(8,2) := 10.25;
v_quantity number(8,0) := 400;
BEGIN
:g_inv_value := v_price * v_quantity;
END;
/
Print g_inv_value
/
Set serveroutput on
DECLARE
v_inv_value number(10,2);
v_price number(8,2) := 10.25;
v_quantity number(8,0) := 400;
BEGIN
v_inv_value := v_price * v_quantity;
dbms_output.put('The value is: ');
dbms_output.put_line(v_inv_value);
END;
/
Set serveroutput on
Accept p_price Prompt 'Enter the Price: '
DECLARE
v_inv_value number(8,2);
v_price number(8,2);
v_quantity number(8,0) := 400;
BEGIN
v_price := &p_price;
v_inv_value := v_price * v_quantity;
dbms_output.put_line('******');
dbms_output.put_line('price * quantity=');
dbms_output.put_line(v_inv_value);
END;
/
Note: PL/SQL not designed for user interface programming
DECLARE
v_salary number(9,2) := 40000;
BEGIN
/* this is a multi-line comment that
will be ignored by the pl/sql
interpreter */
v_salary := v_salary * 2; -- nice raise
END; -- end of program
SET SERVEROUTPUT ON
DECLARE
v_max_gpa number(3,2);
v_numstudents number(4);
v_lname students.lname%type;
v_major students.major%type;
BEGIN
select max(gpa) into v_max_gpa
from students;
DBMS_OUTPUT.PUT_LINE ('The highest GPA is '||v_max_gpa);
select count(sid) into v_numstudents
from students
where gpa = v_max_gpa;
IF v_numstudents > 1 then
DBMS_OUTPUT.PUT_LINE ('There are '||v_numstudents||' with that GPA');
ELSE
select lname, major into v_lname, v_major
from students
where gpa=v_max_gpa;
DBMS_OUTPUT.PUT_LINE ('The student name is '||v_lname);
DBMS_OUTPUT.PUT_LINE ('The student major is '||v_major);
END IF;
END;
/
๏ฝ CHR(asciivalue)
๏ฝ ASCII(string)
๏ฝ LOWER(string)
๏ฝ SUBSTR(string,start,substrlength)
๏ฝ LTRIM(string)
๏ฝ RTRIM(string)
๏ฝ LPAD(string_to_be_padded, spaces_to_pad, |string_to_pad_with|)
๏ฝ RPAD(string_to_be_padded, spaces_to_pad, |string_to_pad_with|)
๏ฝ REPLACE(string, searchstring, replacestring)
๏ฝ UPPER(string)
๏ฝ INITCAP(string)
๏ฝ LENGTH(string)
๏ฝ ABS(value)
๏ฝ ROUND(value, precision)
๏ฝ MOD(value,divisor)
๏ฝ SQRT(value)
๏ฝ TRUNC(value,|precision|)
๏ฝ LEAST(exp1, exp2โ€ฆ)
๏ฝ GREATEST(exp1, exp2โ€ฆ)
Set serveroutput on
DECLARE
v_student students%rowtype;
BEGIN
select * into v_student
from students
where sid='123456';
DBMS_OUTPUT.PUT_LINE (v_student.lname);
DBMS_OUTPUT.PUT_LINE (v_student.major);
DBMS_OUTPUT.PUT_LINE (v_student.gpa);
END;
/
๏ฝ A cursor is a private set of records
๏ฝ An Oracle Cursor = VB recordset = JDBC
ResultSet
๏ฝ Implicit cursors are created for every query made
in Oracle
๏ฝ Explicit cursors can be declared by a programmer
within PL/SQL.
๏ฝ cursorname%ROWCOUNT Rows returned so far
๏ฝ cursorname%FOUND One or more rows retrieved
๏ฝ cursorname%NOTFOUND No rows found
๏ฝ Cursorname%ISOPEN Is the cursor open
๏ฝ Declare the cursor
๏ฝ Open the cursor
๏ฝ Fetch a row
๏ฝ Test for end of cursor
๏ฝ Close the cursor
Note: there is a FOR LOOP available with an implicit fetch
DECLARE
CURSOR students_cursor IS
SELECT * from students;
v_student students_cursor%rowtype;
/* instead we could do v_student students%rowtype */
BEGIN
DBMS_OUTPUT.PUT_LINE ('******************');
OPEN students_cursor;
FETCH students_cursor into v_student;
WHILE students_cursor%found LOOP
DBMS_OUTPUT.PUT_LINE (v_student.last);
DBMS_OUTPUT.PUT_LINE (v_student.major);
DBMS_OUTPUT.PUT_LINE ('******************');
FETCH students_cursor into v_student;
END LOOP;
CLOSE students_cursor;
END;
/
DECLARE
CURSOR students_cursor IS
SELECT last, major from students;
v_Last students.last%type;
v_major students.major%type;
BEGIN
DBMS_OUTPUT.PUT_LINE ('******************');
OPEN students_cursor;
FETCH students_cursor into v_last, v_major;
WHILE students_cursor%found LOOP
DBMS_OUTPUT.PUT_LINE (v_last);
DBMS_OUTPUT.PUT_LINE (v_major);
DBMS_OUTPUT.PUT_LINE ('******************');
FETCH students_cursor into v_last, v_major;
END LOOP;
CLOSE students_cursor;
END;
/
๏ฝ When something is too complicated for SQL
๏ฝ When conditional branching and looping are needed
๏ฝ Example
๏ฝ Write a PL/SQL program that assigns email address to each employee or
student in a table. Following these rules:
- email address should be all lower case
- email address should default to first initial plus the first seven letters of the last name
- email can be no longer than eight characters
- if email is already used than use first initial plus middle initial plus first
six letters of last name
- if the previous address is taken use the first two letters of the first name
and the first six letters of the last name.
- if the previous address is taken use first six letters of last name + 01 or 02 โ€ฆetc
๏ฝ PL/SQL code stored in the database and executed when called by the
user.
๏ฝ Called by procedure name from another PL/SQL block or using EXECUTE
from SQL+. For example EXEC SQR(50)
๏ฝ Example:
Create procedure SQR (v_num_to_square IN number)
AS
v_answer number(10);
BEGIN
v_answer := v_num_to_square * v_num_to_square;
dbms_output.put_line(v_answer);
END;
/
๏ฝ PL/SQL user defined function stored in the database and executed
when a function call is made in code: example x := SQUARED(50)
๏ฝ Example:
Create or Replace Function SQUARED
(p_number_to_square IN number)
RETURN number
IS
v_answer number(10);
BEGIN
v_answer := p_number_to_square * p_number_to_square;
RETURN(v_answer);
END;
/
Create or replace procedure mytabs
AS
CURSOR table_cursor IS
Select table_name from user_tables;
v_tablename varchar2(30);
BEGIN
open table_cursor;
fetch table_cursor into v_tablename;
while table_cursor%found loop
dbms_output.put_line(v_tablename);
fetch table_cursor into v_tablename;
end loop;
close table_cursor;
END;
๏ฝ PL/SQL code executed automatically in response to a database event,
typically DML.
๏ฝ Like other stored procedures, triggers are stored in the database.
๏ฝ Often used to:
โ—ฆ enforce complex constraints, especially multi-table constraints. Financial
posting is an example of this.
โ—ฆ Trigger related actions
โ—ฆ implement auditing โ€œlogsโ€
โ—ฆ pop a sequence when creating token keys
๏ฝ Triggers do not issue transaction control statements (such as commit).
Triggers are part of the SQL transaction that invoked them.
๏ฝ USER_TRIGGERS provides a data dictionary view of triggers.
CREATE OR REPLACE TRIGGER <trigger_name>
[BEFORE/AFTER][DELETE/INSERT/UPDATE of <column_name |, column_nameโ€ฆ |>
ON <table_name>
|FOR EACH ROW|
|WHEN <triggering condition>|
|DECLARE|
BEGIN
trigger statements
โ€ฆโ€ฆโ€ฆโ€ฆ
END;
To delete a trigger use:
DROP TRIGGER <trigger_name>;
CREATE OR REPLACE TRIGGER LOGSTUDENTCHANGES
BEFORE INSERT OR DELETE OR UPDATE of Major ON STUDENTS
FOR EACH ROW
DECLARE
v_ChangeType CHAR(1);
v_sid varchar2(10);
BEGIN
IF INSERTING THEN
V_ChangeType := 'I';
v_sid := :new.sid;
ELSIF UPDATING THEN
V_ChangeType := 'U';
v_sid := :new.sid;
ELSE
V_ChangeType := 'D';
v_sid := :old.sid;
END IF;
INSERT INTO MAJ_AUDIT (change_type, changed_by, timestamp,
SID, old_major, new_major)
VALUES (v_ChangeType, USER, SYSDATE, v_sid, :old.major, :new.major);
END LOGSTUDENTCHANGES;
CREATE OR REPLACE TRIGGER UPPERCASE
BEFORE INSERT OR UPDATE ON STUDENTS
FOR EACH ROW
DECLARE
BEGIN
:new.lastname:=UPPER(:new.lastname);
:new.firstname:=UPPER(:new.firstname);
END UPPERCASE;
/
CREATE OR REPLACE TRIGGER SalaryTrig
BEFORE INSERT ON Employees
FOR EACH ROW
DECLARE
v_upper_sal_limit NUMBER(10,2);
v_lower_sal_limit NUMBER(10,2);
BEGIN
SELECT MIN(salary)*10 INTO v_upper_sal_limit
FROM employees;
SELECT MAX(salary)/10 INTO v_lower_sal_limit
FROM employees;
IF :new.salary NOT BETWEEN v_lower_sal_limit AND v_upper_sal_limit THEN
RAISE_APPLICATION_ERROR(-20001,'salary out of allowed range');
END IF;
END SalaryTrig;
/
Notes: Application error number is a parameter between โ€“20,000 and โ€“20,999.
You could also stop the insert by "poisoning" it, changing a :new
buffer value to one that you know will not pass constraint evaluation.
CREATE SEQUENCE <sequence_name>
|INCREMENT BY <number>|
|START WITH <start_value>|
|MAXVALUE <maximum_value>|NOMAXVALUE|
|MINVALUE <minimum_value>|
|CYCLE|NOCYLE|
|CACHE <number of values>|NOCACHE|
|ORDER|NOORDER|
To pop the next sequence use:
SEQUENCENAME.NEXTVAL (CURRVAL shows last pop)

More Related Content

What's hot

ORACLE PL/SQL
ORACLE PL/SQLORACLE PL/SQL
ORACLE PL/SQLASHABOOPATHY
ย 
06 Using More Package Concepts
06 Using More Package Concepts06 Using More Package Concepts
06 Using More Package Conceptsrehaniltifat
ย 
08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadata08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadatarehaniltifat
ย 
PL/SQL Fundamentals I
PL/SQL Fundamentals IPL/SQL Fundamentals I
PL/SQL Fundamentals INick Buytaert
ย 
PL/SQL TRIGGERS
PL/SQL TRIGGERSPL/SQL TRIGGERS
PL/SQL TRIGGERSLakshman Basnet
ย 
Triggers
TriggersTriggers
TriggersPooja Dixit
ย 
04 Handling Exceptions
04 Handling Exceptions04 Handling Exceptions
04 Handling Exceptionsrehaniltifat
ย 
JavaScript Control Statements II
JavaScript Control Statements IIJavaScript Control Statements II
JavaScript Control Statements IIReem Alattas
ย 
Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Salman Memon
ย 
Packages in PL/SQL
Packages in PL/SQLPackages in PL/SQL
Packages in PL/SQLPooja Dixit
ย 
SQL Functions
SQL FunctionsSQL Functions
SQL Functionsammarbrohi
ย 
10 Creating Triggers
10 Creating Triggers10 Creating Triggers
10 Creating Triggersrehaniltifat
ย 
09 Managing Dependencies
09 Managing Dependencies09 Managing Dependencies
09 Managing Dependenciesrehaniltifat
ย 
Literals,variables,datatype in C#
Literals,variables,datatype in C#Literals,variables,datatype in C#
Literals,variables,datatype in C#Prasanna Kumar SM
ย 
PLSQL Cursors
PLSQL CursorsPLSQL Cursors
PLSQL Cursorsspin_naresh
ย 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorialRumman Ansari
ย 
Exception handling in plsql
Exception handling in plsqlException handling in plsql
Exception handling in plsqlArun Sial
ย 

What's hot (20)

ORACLE PL/SQL
ORACLE PL/SQLORACLE PL/SQL
ORACLE PL/SQL
ย 
06 Using More Package Concepts
06 Using More Package Concepts06 Using More Package Concepts
06 Using More Package Concepts
ย 
PLSQL Tutorial
PLSQL TutorialPLSQL Tutorial
PLSQL Tutorial
ย 
08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadata08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadata
ย 
PL/SQL Fundamentals I
PL/SQL Fundamentals IPL/SQL Fundamentals I
PL/SQL Fundamentals I
ย 
Introduction to triggers
Introduction to triggersIntroduction to triggers
Introduction to triggers
ย 
PL/SQL TRIGGERS
PL/SQL TRIGGERSPL/SQL TRIGGERS
PL/SQL TRIGGERS
ย 
Triggers
TriggersTriggers
Triggers
ย 
04 Handling Exceptions
04 Handling Exceptions04 Handling Exceptions
04 Handling Exceptions
ย 
JavaScript Control Statements II
JavaScript Control Statements IIJavaScript Control Statements II
JavaScript Control Statements II
ย 
Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Including Constraints -Oracle Data base
Including Constraints -Oracle Data base
ย 
Packages in PL/SQL
Packages in PL/SQLPackages in PL/SQL
Packages in PL/SQL
ย 
SQL Functions
SQL FunctionsSQL Functions
SQL Functions
ย 
10 Creating Triggers
10 Creating Triggers10 Creating Triggers
10 Creating Triggers
ย 
09 Managing Dependencies
09 Managing Dependencies09 Managing Dependencies
09 Managing Dependencies
ย 
Literals,variables,datatype in C#
Literals,variables,datatype in C#Literals,variables,datatype in C#
Literals,variables,datatype in C#
ย 
PLSQL Cursors
PLSQL CursorsPLSQL Cursors
PLSQL Cursors
ย 
Stored procedures
Stored proceduresStored procedures
Stored procedures
ย 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
ย 
Exception handling in plsql
Exception handling in plsqlException handling in plsql
Exception handling in plsql
ย 

Viewers also liked

Windows7technicianjun
Windows7technicianjunWindows7technicianjun
Windows7technicianjunJavaKid Indhu
ย 
Apache hadoop basics
Apache hadoop basicsApache hadoop basics
Apache hadoop basicssaili mane
ย 
Reject the reformation, reap the revolution
Reject the reformation, reap the revolutionReject the reformation, reap the revolution
Reject the reformation, reap the revolutionAngie Love Colinares
ย 
Cloud computing simplified...
Cloud computing simplified...Cloud computing simplified...
Cloud computing simplified...saili mane
ย 
Agile project management
Agile project managementAgile project management
Agile project managementsaili mane
ย 
Intranet mailing system
Intranet mailing systemIntranet mailing system
Intranet mailing systemsaili mane
ย 
Cisco ERP Implementation
Cisco ERP ImplementationCisco ERP Implementation
Cisco ERP Implementationsaili mane
ย 

Viewers also liked (10)

Windows7technicianjun
Windows7technicianjunWindows7technicianjun
Windows7technicianjun
ย 
Apache hadoop basics
Apache hadoop basicsApache hadoop basics
Apache hadoop basics
ย 
Reject the reformation, reap the revolution
Reject the reformation, reap the revolutionReject the reformation, reap the revolution
Reject the reformation, reap the revolution
ย 
Presentation1
Presentation1Presentation1
Presentation1
ย 
Cloud computing simplified...
Cloud computing simplified...Cloud computing simplified...
Cloud computing simplified...
ย 
Agile project management
Agile project managementAgile project management
Agile project management
ย 
Pipelining
PipeliningPipelining
Pipelining
ย 
Animation
AnimationAnimation
Animation
ย 
Intranet mailing system
Intranet mailing systemIntranet mailing system
Intranet mailing system
ย 
Cisco ERP Implementation
Cisco ERP ImplementationCisco ERP Implementation
Cisco ERP Implementation
ย 

Similar to PLSQL

PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts Bharat Kalia
ย 
L9 l10 server side programming
L9 l10  server side programmingL9 l10  server side programming
L9 l10 server side programmingRushdi Shams
ย 
Open Gurukul Language PL/SQL
Open Gurukul Language PL/SQLOpen Gurukul Language PL/SQL
Open Gurukul Language PL/SQLOpen Gurukul
ย 
Module04
Module04Module04
Module04Sridhar P
ย 
Dynamic websites lec3
Dynamic websites lec3Dynamic websites lec3
Dynamic websites lec3Belal Arfa
ย 
PL-SQL.pdf
PL-SQL.pdfPL-SQL.pdf
PL-SQL.pdfAnas Nakash
ย 
Procedures/functions of rdbms
Procedures/functions of rdbmsProcedures/functions of rdbms
Procedures/functions of rdbmsjain.pralabh
ย 
plsql.ppt
plsql.pptplsql.ppt
plsql.pptfaizan992426
ย 
Tony jambu (obscure) tools of the trade for tuning oracle sq ls
Tony jambu   (obscure) tools of the trade for tuning oracle sq lsTony jambu   (obscure) tools of the trade for tuning oracle sq ls
Tony jambu (obscure) tools of the trade for tuning oracle sq lsInSync Conference
ย 
PLSQLmy Updated (1).pptx
PLSQLmy Updated (1).pptxPLSQLmy Updated (1).pptx
PLSQLmy Updated (1).pptxvamsiyadav39
ย 
PLSQL.pptx
PLSQL.pptxPLSQL.pptx
PLSQL.pptxgit21is061t
ย 
Relational Database Management System
Relational Database Management SystemRelational Database Management System
Relational Database Management Systemsweetysweety8
ย 
Procedure n functions
Procedure n functionsProcedure n functions
Procedure n functionsKhadija Parween
ย 
Unit 3(rdbms)
Unit 3(rdbms)Unit 3(rdbms)
Unit 3(rdbms)Jay Patel
ย 
Unit 3(rdbms)
Unit 3(rdbms)Unit 3(rdbms)
Unit 3(rdbms)Jay Patel
ย 
Mysqlppt
MysqlpptMysqlppt
MysqlpptReka
ย 

Similar to PLSQL (20)

PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts
ย 
SQL- Introduction to PL/SQL
SQL- Introduction to  PL/SQLSQL- Introduction to  PL/SQL
SQL- Introduction to PL/SQL
ย 
Plsql
PlsqlPlsql
Plsql
ย 
L9 l10 server side programming
L9 l10  server side programmingL9 l10  server side programming
L9 l10 server side programming
ย 
Open Gurukul Language PL/SQL
Open Gurukul Language PL/SQLOpen Gurukul Language PL/SQL
Open Gurukul Language PL/SQL
ย 
Module04
Module04Module04
Module04
ย 
Dynamic websites lec3
Dynamic websites lec3Dynamic websites lec3
Dynamic websites lec3
ย 
PL-SQL.pdf
PL-SQL.pdfPL-SQL.pdf
PL-SQL.pdf
ย 
Procedures/functions of rdbms
Procedures/functions of rdbmsProcedures/functions of rdbms
Procedures/functions of rdbms
ย 
plsql.ppt
plsql.pptplsql.ppt
plsql.ppt
ย 
Tony jambu (obscure) tools of the trade for tuning oracle sq ls
Tony jambu   (obscure) tools of the trade for tuning oracle sq lsTony jambu   (obscure) tools of the trade for tuning oracle sq ls
Tony jambu (obscure) tools of the trade for tuning oracle sq ls
ย 
PLSQLmy Updated (1).pptx
PLSQLmy Updated (1).pptxPLSQLmy Updated (1).pptx
PLSQLmy Updated (1).pptx
ย 
PLSQL.pptx
PLSQL.pptxPLSQL.pptx
PLSQL.pptx
ย 
Relational Database Management System
Relational Database Management SystemRelational Database Management System
Relational Database Management System
ย 
Procedure n functions
Procedure n functionsProcedure n functions
Procedure n functions
ย 
Unit 3
Unit 3Unit 3
Unit 3
ย 
Unit 3(rdbms)
Unit 3(rdbms)Unit 3(rdbms)
Unit 3(rdbms)
ย 
Unit 3(rdbms)
Unit 3(rdbms)Unit 3(rdbms)
Unit 3(rdbms)
ย 
SQL / PL
SQL / PLSQL / PL
SQL / PL
ย 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
ย 

Recently uploaded

Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
ย 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
ย 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfKamal Acharya
ย 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)simmis5
ย 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxfenichawla
ย 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
ย 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdfKamal Acharya
ย 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
ย 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
ย 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
ย 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...SUHANI PANDEY
ย 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
ย 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
ย 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
ย 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
ย 
Top Rated Pune Call Girls Budhwar Peth โŸŸ 6297143586 โŸŸ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth โŸŸ 6297143586 โŸŸ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth โŸŸ 6297143586 โŸŸ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth โŸŸ 6297143586 โŸŸ Call Me For Genuine Se...Call Girls in Nagpur High Profile
ย 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...Call Girls in Nagpur High Profile
ย 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
ย 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . pptDineshKumar4165
ย 

Recently uploaded (20)

Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
ย 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
ย 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ย 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
ย 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
ย 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
ย 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
ย 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ย 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
ย 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
ย 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
ย 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
ย 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
ย 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
ย 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
ย 
Top Rated Pune Call Girls Budhwar Peth โŸŸ 6297143586 โŸŸ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth โŸŸ 6297143586 โŸŸ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth โŸŸ 6297143586 โŸŸ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth โŸŸ 6297143586 โŸŸ Call Me For Genuine Se...
ย 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
ย 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
ย 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
ย 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
ย 

PLSQL

  • 1.
  • 2. ๏ฝ Procedural Language โ€“ SQL ๏ฝ An extension to SQL with design features of programming languages (procedural and object oriented) ๏ฝ PL/SQL and Java are both supported as internal host languages within Oracle products.
  • 3. ๏ฝ Acts as host language for stored procedures and triggers. ๏ฝ Provides the ability to add middle tier business logic to client/server applications. ๏ฝ Provides Portability of code from one environment to another ๏ฝ Improves performance of multi-query transactions. ๏ฝ Provides error handling
  • 4. DECLARE (optional) - variable declarations BEGIN (required) - SQL statements - PL/SQL statements or sub-blocks EXCEPTION (optional) - actions to perform when errors occur END; (required)
  • 6. ๏ฝ Scalar (char, varchar2, number, date, etc) ๏ฝ Composite (%rowtype) ๏ฝ Reference (pointers) ๏ฝ LOB (large objects) Note: Non PL/SQL variables include bind variables, host (โ€œglobalโ€) variables, and parameters.
  • 7. ๏ฝ Two variables can have the same name if they are in different blocks (bad idea) ๏ฝ The variable name should not be the same as any table column names used in the block.
  • 8. ๏ฝ All variables must be declared before their use. ๏ฝ The assignment statement : = is not the same as the equality operator = ๏ฝ All statements end with a ;
  • 9. Variable g_inv_value number DECLARE v_price number(8,2) := 10.25; v_quantity number(8,0) := 400; BEGIN :g_inv_value := v_price * v_quantity; END; / Print g_inv_value /
  • 10. Set serveroutput on DECLARE v_inv_value number(10,2); v_price number(8,2) := 10.25; v_quantity number(8,0) := 400; BEGIN v_inv_value := v_price * v_quantity; dbms_output.put('The value is: '); dbms_output.put_line(v_inv_value); END; /
  • 11. Set serveroutput on Accept p_price Prompt 'Enter the Price: ' DECLARE v_inv_value number(8,2); v_price number(8,2); v_quantity number(8,0) := 400; BEGIN v_price := &p_price; v_inv_value := v_price * v_quantity; dbms_output.put_line('******'); dbms_output.put_line('price * quantity='); dbms_output.put_line(v_inv_value); END; / Note: PL/SQL not designed for user interface programming
  • 12. DECLARE v_salary number(9,2) := 40000; BEGIN /* this is a multi-line comment that will be ignored by the pl/sql interpreter */ v_salary := v_salary * 2; -- nice raise END; -- end of program
  • 13. SET SERVEROUTPUT ON DECLARE v_max_gpa number(3,2); v_numstudents number(4); v_lname students.lname%type; v_major students.major%type; BEGIN select max(gpa) into v_max_gpa from students; DBMS_OUTPUT.PUT_LINE ('The highest GPA is '||v_max_gpa); select count(sid) into v_numstudents from students where gpa = v_max_gpa; IF v_numstudents > 1 then DBMS_OUTPUT.PUT_LINE ('There are '||v_numstudents||' with that GPA'); ELSE select lname, major into v_lname, v_major from students where gpa=v_max_gpa; DBMS_OUTPUT.PUT_LINE ('The student name is '||v_lname); DBMS_OUTPUT.PUT_LINE ('The student major is '||v_major); END IF; END; /
  • 14. ๏ฝ CHR(asciivalue) ๏ฝ ASCII(string) ๏ฝ LOWER(string) ๏ฝ SUBSTR(string,start,substrlength) ๏ฝ LTRIM(string) ๏ฝ RTRIM(string) ๏ฝ LPAD(string_to_be_padded, spaces_to_pad, |string_to_pad_with|) ๏ฝ RPAD(string_to_be_padded, spaces_to_pad, |string_to_pad_with|) ๏ฝ REPLACE(string, searchstring, replacestring) ๏ฝ UPPER(string) ๏ฝ INITCAP(string) ๏ฝ LENGTH(string)
  • 15. ๏ฝ ABS(value) ๏ฝ ROUND(value, precision) ๏ฝ MOD(value,divisor) ๏ฝ SQRT(value) ๏ฝ TRUNC(value,|precision|) ๏ฝ LEAST(exp1, exp2โ€ฆ) ๏ฝ GREATEST(exp1, exp2โ€ฆ)
  • 16. Set serveroutput on DECLARE v_student students%rowtype; BEGIN select * into v_student from students where sid='123456'; DBMS_OUTPUT.PUT_LINE (v_student.lname); DBMS_OUTPUT.PUT_LINE (v_student.major); DBMS_OUTPUT.PUT_LINE (v_student.gpa); END; /
  • 17. ๏ฝ A cursor is a private set of records ๏ฝ An Oracle Cursor = VB recordset = JDBC ResultSet ๏ฝ Implicit cursors are created for every query made in Oracle ๏ฝ Explicit cursors can be declared by a programmer within PL/SQL.
  • 18. ๏ฝ cursorname%ROWCOUNT Rows returned so far ๏ฝ cursorname%FOUND One or more rows retrieved ๏ฝ cursorname%NOTFOUND No rows found ๏ฝ Cursorname%ISOPEN Is the cursor open
  • 19. ๏ฝ Declare the cursor ๏ฝ Open the cursor ๏ฝ Fetch a row ๏ฝ Test for end of cursor ๏ฝ Close the cursor Note: there is a FOR LOOP available with an implicit fetch
  • 20. DECLARE CURSOR students_cursor IS SELECT * from students; v_student students_cursor%rowtype; /* instead we could do v_student students%rowtype */ BEGIN DBMS_OUTPUT.PUT_LINE ('******************'); OPEN students_cursor; FETCH students_cursor into v_student; WHILE students_cursor%found LOOP DBMS_OUTPUT.PUT_LINE (v_student.last); DBMS_OUTPUT.PUT_LINE (v_student.major); DBMS_OUTPUT.PUT_LINE ('******************'); FETCH students_cursor into v_student; END LOOP; CLOSE students_cursor; END; /
  • 21. DECLARE CURSOR students_cursor IS SELECT last, major from students; v_Last students.last%type; v_major students.major%type; BEGIN DBMS_OUTPUT.PUT_LINE ('******************'); OPEN students_cursor; FETCH students_cursor into v_last, v_major; WHILE students_cursor%found LOOP DBMS_OUTPUT.PUT_LINE (v_last); DBMS_OUTPUT.PUT_LINE (v_major); DBMS_OUTPUT.PUT_LINE ('******************'); FETCH students_cursor into v_last, v_major; END LOOP; CLOSE students_cursor; END; /
  • 22. ๏ฝ When something is too complicated for SQL ๏ฝ When conditional branching and looping are needed ๏ฝ Example ๏ฝ Write a PL/SQL program that assigns email address to each employee or student in a table. Following these rules: - email address should be all lower case - email address should default to first initial plus the first seven letters of the last name - email can be no longer than eight characters - if email is already used than use first initial plus middle initial plus first six letters of last name - if the previous address is taken use the first two letters of the first name and the first six letters of the last name. - if the previous address is taken use first six letters of last name + 01 or 02 โ€ฆetc
  • 23. ๏ฝ PL/SQL code stored in the database and executed when called by the user. ๏ฝ Called by procedure name from another PL/SQL block or using EXECUTE from SQL+. For example EXEC SQR(50) ๏ฝ Example: Create procedure SQR (v_num_to_square IN number) AS v_answer number(10); BEGIN v_answer := v_num_to_square * v_num_to_square; dbms_output.put_line(v_answer); END; /
  • 24. ๏ฝ PL/SQL user defined function stored in the database and executed when a function call is made in code: example x := SQUARED(50) ๏ฝ Example: Create or Replace Function SQUARED (p_number_to_square IN number) RETURN number IS v_answer number(10); BEGIN v_answer := p_number_to_square * p_number_to_square; RETURN(v_answer); END; /
  • 25. Create or replace procedure mytabs AS CURSOR table_cursor IS Select table_name from user_tables; v_tablename varchar2(30); BEGIN open table_cursor; fetch table_cursor into v_tablename; while table_cursor%found loop dbms_output.put_line(v_tablename); fetch table_cursor into v_tablename; end loop; close table_cursor; END;
  • 26. ๏ฝ PL/SQL code executed automatically in response to a database event, typically DML. ๏ฝ Like other stored procedures, triggers are stored in the database. ๏ฝ Often used to: โ—ฆ enforce complex constraints, especially multi-table constraints. Financial posting is an example of this. โ—ฆ Trigger related actions โ—ฆ implement auditing โ€œlogsโ€ โ—ฆ pop a sequence when creating token keys ๏ฝ Triggers do not issue transaction control statements (such as commit). Triggers are part of the SQL transaction that invoked them. ๏ฝ USER_TRIGGERS provides a data dictionary view of triggers.
  • 27. CREATE OR REPLACE TRIGGER <trigger_name> [BEFORE/AFTER][DELETE/INSERT/UPDATE of <column_name |, column_nameโ€ฆ |> ON <table_name> |FOR EACH ROW| |WHEN <triggering condition>| |DECLARE| BEGIN trigger statements โ€ฆโ€ฆโ€ฆโ€ฆ END; To delete a trigger use: DROP TRIGGER <trigger_name>;
  • 28. CREATE OR REPLACE TRIGGER LOGSTUDENTCHANGES BEFORE INSERT OR DELETE OR UPDATE of Major ON STUDENTS FOR EACH ROW DECLARE v_ChangeType CHAR(1); v_sid varchar2(10); BEGIN IF INSERTING THEN V_ChangeType := 'I'; v_sid := :new.sid; ELSIF UPDATING THEN V_ChangeType := 'U'; v_sid := :new.sid; ELSE V_ChangeType := 'D'; v_sid := :old.sid; END IF; INSERT INTO MAJ_AUDIT (change_type, changed_by, timestamp, SID, old_major, new_major) VALUES (v_ChangeType, USER, SYSDATE, v_sid, :old.major, :new.major); END LOGSTUDENTCHANGES;
  • 29. CREATE OR REPLACE TRIGGER UPPERCASE BEFORE INSERT OR UPDATE ON STUDENTS FOR EACH ROW DECLARE BEGIN :new.lastname:=UPPER(:new.lastname); :new.firstname:=UPPER(:new.firstname); END UPPERCASE; /
  • 30. CREATE OR REPLACE TRIGGER SalaryTrig BEFORE INSERT ON Employees FOR EACH ROW DECLARE v_upper_sal_limit NUMBER(10,2); v_lower_sal_limit NUMBER(10,2); BEGIN SELECT MIN(salary)*10 INTO v_upper_sal_limit FROM employees; SELECT MAX(salary)/10 INTO v_lower_sal_limit FROM employees; IF :new.salary NOT BETWEEN v_lower_sal_limit AND v_upper_sal_limit THEN RAISE_APPLICATION_ERROR(-20001,'salary out of allowed range'); END IF; END SalaryTrig; / Notes: Application error number is a parameter between โ€“20,000 and โ€“20,999. You could also stop the insert by "poisoning" it, changing a :new buffer value to one that you know will not pass constraint evaluation.
  • 31. CREATE SEQUENCE <sequence_name> |INCREMENT BY <number>| |START WITH <start_value>| |MAXVALUE <maximum_value>|NOMAXVALUE| |MINVALUE <minimum_value>| |CYCLE|NOCYLE| |CACHE <number of values>|NOCACHE| |ORDER|NOORDER| To pop the next sequence use: SEQUENCENAME.NEXTVAL (CURRVAL shows last pop)