SlideShare a Scribd company logo
1 of 33
Inroduction to PL/SQL
1
PL/SQL BLOCK
2
Conditional statements
4
Data type and Variables
3
Loop statements
5
CONTENTS
PL/SQL CURSOR
6
PL/SQL Procedure/Function
7
I
mplicit Cursors
E
xplicit Cursors
8 References
PL/SQL (procedural language extensions to the Structured Query
Language) that allows developers to combine the power of SQL with
procedural statements.
It allows writing a piece of code, including the SQL query in a block
(which is the basic unit of it).
It is a high standard and readable language, so it is very easy to
understand and learn.
It provides the facility to developers to use loops, conditions, object-
oriented concepts and SQL.
Before this, only one query is sent to the Oracle server, which
increases the load and time. But through this, multiple SQL
statements are grouped and sent in a single block or subprogram,
which increases the processing speed and decreases the traffic on
Oracle Server.
1.
2.
3.
4.
5.
PL-SQL
more...
PL/SQL BLOCK
It is the main part that contains all the code. The actual input
contains the SQL statements and the instructions that will interact
with the database.
DECLARE - - (optional)
/* Here you declare the variables you will use in this block
*/
BEGIN - - (mandatory)
/* Here you define the executable statements (what the
block DOES!)*/
EXCEPTION - - (optional)
/* Here you define the actions that take place if an
exception is thrown during the run of this block */
END; - - (mandatory)
SELECT, INSERT, UPDATE, DELETE are supported.
The SELECT statement has a special form in
which a single tuple is placed in variables
Data definition statements like CREATE, DROP, or
ALTER are not allowed.
PL/SQL is not case sensitive.
DECLARE
l_emp_name varchar(20);
BEGIN
SELECT fname INTO l_emp_name
FROM emp
WHERE ssn= 123456789;
dbms_output.put_line( l_emp_name );
END;
EXECUTABLE SECTION
DATA TYPE AND VARIABLES
Use of Data-Types
<variable-name> <datatype> [not null][: =<initial-value>];
<constant-name> constant <datatype> : = <value>;
Number – used to store any number
Char - is a fixed-length data type that contains a constant
number of characters.
Varchar2 - is a variable-length data type that does not
contain a constant number of characters.
Date – used to store dates.
The most common data types :
more...
Radius: 9.5
Diameter: 19
Circumference: 59.69
Area: 283.53
DECLARE
pi constant number := 3.141592654;
radius number(5,2);
dia number(5,2);
circumference number(7, 2);
area number (10, 2);
BEGIN
radius := 9.5;
dia := radius * 2;
circumference := 2.0 * pi * radius;
area := pi * radius * radius;
dbms_output.put_line('Radius: ' || radius);
dbms_output.put_line('Diameter: ' || dia);
dbms_output.put_line('Circumference: ' || circumference);
dbms_output.put_line('Area: ' || area);
END;
A Simple Program to Calculate the Circumference
and Area of a Circle
OUTPUT
DATA TYPE AND VARIABLES
Anchored Data Type
<variable-name> <object>%type [not null][: =<initial-value>];
This another data type could be a column in the
database, thereby providing the ability to match the
data types of PL/SQL variables with the data types of
columns defined in the database.
<variable-name> <object>%rowtype [not null][: =<initial-value>];
%TYPE: is used to refer to a previously declared type which is
given to an attribute of a table or a variable.
%ROWTYPE: returns the record type corresponding to the type
of the rows of a table or a cursor.
DECLARE
num number :=10;
x num%type := 20;
name employee.fname%type := 'Ahmad';
P1 project%rowtype;
BEGIN
dbms_output.put_line('num: ' || num);
dbms_output.put_line('x: ' || x);
dbms_output.put_line('name: ' || name);
SELECT Pname , Plocation INTO P1.pname , P1.plocation FROM project
WHERE Pnumber=10;
dbms_output.put_line('P1.Name: ' || P1.pname || CHR(10) || 'P1.Plocation: ' || P1.Plocation);
- - CHR(10) --->> New line
EXCEPTION
WHEN NO_DATA_FOUND THEN
dbms_output.put_line(SQLERRM);
WHEN TOO_MANY_ROWS THEN
dbms_output.put_line(SQLERRM);
END;
num: 10
x: 20
name: Ahmad
P1.Name: Computerization
P1.pLocation: Stafford
OUTPUT
Example
Some PL / SQL - operators
PL/SQL If
Syntax: (IF-THEN-ELSE statement):
IF condition
THEN
{...statements to execute when condition is TRUE...}
ELSE
{...statements to execute when condition is FALSE...}
END IF;
DECLARE
emp_salary number:= :EnterSalary; -- Input from the user
Increment number := 0;
BEGIN
IF emp_salary>1000 THEN
Increment :=emp_salary * 10/100;
ELSE
Increment :=emp_salary * 5/100;
END IF;
dbms_output.put_line('The salary after the increase is ' || (Increment+emp_salary));
END;
Syntax (IF-THEN-ELSIF-ELSE) : DECLARE
grade char(1) := :EnterGrade;
BEGIN
IF gr
ade = 'A' THEN
dbms_output.put_line('Excellent');
ELSIF gr
ade = 'B' THEN
dbms_output.put_
line('Very good');
ELSIF gr
ade = 'C' THEN
dbms_output.put_
line('Good');
ELSIF gr
ade = 'D' THEN
dbms_output.put_
line('Fair');
ELSE
dbms_ou
tput.put_
line('Fail');
END IF;
END;
IF condition 1
THEN
{...statements to execute when condition1 is TRUE...}
ELSIF condition2
THEN
{...statements to execute when condition2 is TRUE...}
ELSE
{...statements to execute when if all of the previous
. conditions are false...}
END IF;
PL/SQL If
PL/SQL Case Statement
Syntax for the CASE statement:DECLARE
dayOfWeek char(1) ;
BEGIN
SELECT TO_CHAR(SYSDATE, 'D') INTO dayOfWeek
FROM DUAL;
CASE day
OfWeek
WHEN 1 THEN dbms_output.put_line('Today is Sunday');
WHEN 2 THEN dbms
_output.put_line('Today is Monday');
WHEN 3 THEN dbms
_output.put_line('Today is Tuesday');
WHEN 4 THEN dbms
_output.put_line('Today is Wednesday');
WHEN 5 THEN dbms
_output.put_line('Today is Thursday');
WHEN 6 THEN dbms
_output.put_line('Today is Friday');
WHEN 7 THEN dbms
_output.put_line('Today is Saturday');
ELSE
dbms_ou
tput.put_
line('Error');
END CASE;
END;
CASE (Expression)
WHEN condition_1 TH
EN result_1
WHEN condition_2 TH
EN result_3
WHEN condition_3 TH
EN resu
lt_3
ELSE result
END CASE;
PL/SQL Case Statement
Another Use Of CASE
SELECT Fname,Lname,salary,
CASE
WHEN salary >= 5000
THEN 'High Salary'
WHEN salary >= 3000
THEN 'Medium Salary'
ELSE 'Low Salary'
END AS SALARY_CATEGORY
FROM Employee;
SELECT fname,lname,
CASE
WHEN age >= 60 AND SEX = 'M'
THEN 'Elderly Male'
WHEN age >= 60 AND SEX = 'F'
THEN 'Elderly Female '
WHEN age < 60 AND SEX = 'M'
THEN 'Senior Male'
WHEN age < 60 AND SEX = 'F'
THEN 'Senior Female'
ELSE 'Unknown'
END as age_gender
FROM employee;
PL/SQL Exit Loop (Basic Loop)
Syntax of exit loop: DECLARE
sumn number := 0 ;
counter number := 1;
BEGIN
LOOP
sumn := sumn + counter;
counter := counter + 1;
IF counter > 10 THEN
EXIT;
END IF;
END LOOP;
dbms
_output.put_line('The sum is :' || sumn);
END;
LOOP
statements;
EXIT;
{or EXIT WHEN condition;}
END LOOP;
The sum is : 55
OUTPUT
PL/SQL While Loop
Syntax of while loop: - - Calculating even numbers between 1 and 100
DECLARE
counter number := 1 ;
sumn number := 0;
BEGIN
WHILE counter <= 100 LOOP
IF counter MOD 2 = 0 THEN
sumn := sumn + counter;
END I
F;
counter := counter + 1;
END LOOP;
dbms
_output.put_line('The sum is:' || sumn);
END;
WHILE
<condition>;
LOOP statements;
END LOOP;
The sum is : 2550
OUTPUT
PL/SQL FOR Loop
Syntax of for loop: - - Prints a multiplication table for numbers from 1 to 5
DECLARE
result number := 0 ;
BEGIN
FOR i IN 1 .. 5 LOOP
FOR y IN 1 .. 10 LOOP
result := i * y;
dbms
_output.
put_line(i || ' x ' ||y || ' = ' || result);
END LOOP;
END LOO
P;
END;
FOR counter IN initial .. final
LOOP
LOOP statements;
END LOOP;
PL/SQL Cursor
PL/SQL cursor is a pointer that points to a result of a
query. It contains information on a select statement
and the rows of data accessed by it.
A cursor is used to fetch and process the rows
returned by the SQL statement, one at a time.
There are two types of cursors: explicit and implicit.
PL/SQL Cursor
1) PL/SQL Implicit Cursors
The implicit cursors are automatically generated by
Oracle while an SQL statement is executed, if you don't
use an explicit cursor for the statement.
These are created by default to process the statements
when DML statements like INSERT, UPDATE, DELETE
etc. are executed.
PL/SQL Cursor
The following table specifies the status of the
cursor with each of its attribute.
PL/SQL Cursor
DECLARE
total_rows number(2);
BEGIN
UPDATE employee
SET salary = salary + 1000 WHERE salary <= 3000;
IF SQL%NOTFOUND THEN
dbms_output.put_line('no customers updated');
ELSIF SQL%FOUND THEN
total_rows := SQL%ROWCOUNT;
dbms_output.put_line( total_rows || ' customers updated ');
END IF;
END;
Example on Implicit Cursors:
CLOSE
EMPTY?
DECLARE OPEN FETCH
NO
YES
PL/SQL Cursor
2) PL/SQL Explicit Cursors
The Explicit cursors are defined by the programmers to gain more
control over the context area.
These cursors should be defined in the declaration section of the
PL/SQL block.
It is created on a SELECT statement which returns more than one
row.
PL/SQL Cursor
Controlling Explicit Cursors
PL/SQL Cursor
Example on Explicit Cursors:
DECLARE
ssn_var employee.ssn%type;
name_var employee.fname%type;
addr_var employee.address%type;
CURSOR M_employee IS
SELECT ssn, fname, address
FROM employee
WHERE sex='M';
BEGIN
OPEN M_employee;
LOOP
FETCH M_employee INTO
ssn_var, name_var, addr_var;
EXIT WHEN M_employee%notfound;
dbms_output.put_line(ssn_var || ' ' ||
name_var || ' ' || addr_var);
END LOOP;
CLOSE M_employee;
END;
PL/SQL Procedure
The PL/SQL stored procedure or simply a procedure is a PL/SQL
block which performs one or more specific tasks. It is just like
procedures in other programming languages.
IN parameters: These can be referenced by the procedure
or function, but their values cannot be overwritten.
OUT parameters: These cannot be referenced by the
procedure or function, but their values can be overwritten.
IN OUT parameters: These can be referenced by the
procedure or function and their values can be overwritten.
1.
2.
3.
How to pass parameters in procedure(modes of parameter):
PL/SQL Procedure
Syntax for creating Procedure:
CREATE [OR REPLACE] PROCEDURE procedure_name
[ (parameter1 [mode] datatype1,
parameter2 [mode] datatype2, . . . ) ]
IS | AS - - default of mode is IN
[declaration_section]
BEGIN
executable_section
END [procedure_name];
PL/SQL Procedure
create or replace procedure print_emp_S(p_ssn employee.superssn%type)
IS
CURSOR info_E IS
SELECT fname,lname,salary
FROM employee WHERE superssn = p_ssn;
BEGIN
FOR i IN info_E
LOOP
dbms_output.put_line(i.fname || i.lname || i.salary);
END LOOP;
END;
Example on Procedure :
Exercise
PL/SQL Procedure
Write PL/SQL code to update the commission value for all the
employees working in a specific department according to the
following formulas:
1- if the Employee department is 'Administration', let the commission
to be 10% of the salary value.
2-if the Employee department is 'Headquarters', let the commission
to be 5 % of the salary value.
3-otherwise, let it 2 % of the salary value.
Solution
create or replace procedure up_sal
IS
CURSOR cu_get_emp_d IS
select salary , Dname ,ssn
from employee e JOIN department d
ON e.Dno = d.Dnumber;
salComm_var number;
BEGIN
FOR var IN cu_get_emp_d LOOP
IF var.Dname= 'Administration'
THEN salComm_var := var.salary * 0.10;
ELSIF var.Dname= 'Headquarters'
THEN salComm_var := var.salary * 0.05;
ELSE
salComm_var := var.salary * 0.02;
END IF;
update employee
set salary = salary + salComm_var
where ssn = var.ssn ;
END LOOP;
END ;
PL/SQL Procedure
PL/SQL Function
CREATE [OR REPLACE] FUNCTION Function_name
[ (parameter1 [mode] datatype1,
parameter2 [mode] datatype2, . . . ) ] RETURN data_type
IS | AS - - default of mode is IN
[declaration_section]
BEGIN
executable_section
RETURN value
END [function_name];
Syntax for creating Function:
PL/SQL Function
Example on Function:
create or replace function customerOfCategory
(T_P IN number)return varchar IS
c_BRONZE_RATING number(4) := 200;
c_SILVER_RATING number(4) := 500;
BEGIN
IF T_P <= c_BRONZE_RATING THEN
return 'The customer is a BRONZE';
ELSIF T_P <= c_SILVER_RATING THEN
return 'The customer is a SILVER';
ELSE
return 'The customer is a GOLD';
END IF;
END;
DECLARE
-- Input from the user
total number(4) := :Enter_Total_purchases;
get varchar(50);
BEGIN
get := customerOf
Category(total);
dbms_output.put_line(get);
EXCEPTION
WHEN VALUE_ERROR THEN
dbms_output.put_line('An error
occurred: ' || SQLERRM);
END;
References
https://www.javatpoint.com/pl-sql-tutorial
https://www.educba.com/software-
development/software-development-
tutorials/pl-sql-tutorial/
https://www.oracletutorial.com/plsql-
tutorial/

More Related Content

Similar to PL-SQL.pdf

Similar to PL-SQL.pdf (20)

Unit 3(rdbms)
Unit 3(rdbms)Unit 3(rdbms)
Unit 3(rdbms)
 
PLSQL (1).ppt
PLSQL (1).pptPLSQL (1).ppt
PLSQL (1).ppt
 
PLSQL Note
PLSQL NotePLSQL Note
PLSQL Note
 
PLSQL
PLSQLPLSQL
PLSQL
 
Oracle - Program with PL/SQL - Lession 01
Oracle - Program with PL/SQL - Lession 01Oracle - Program with PL/SQL - Lession 01
Oracle - Program with PL/SQL - Lession 01
 
Oracle pl sql
Oracle pl sqlOracle pl sql
Oracle pl sql
 
Plsql
PlsqlPlsql
Plsql
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
 
Oracle
OracleOracle
Oracle
 
SQL / PL
SQL / PLSQL / PL
SQL / PL
 
Database Management System
Database Management SystemDatabase Management System
Database Management System
 
Oracle - Program with PL/SQL - Lession 09
Oracle - Program with PL/SQL - Lession 09Oracle - Program with PL/SQL - Lession 09
Oracle - Program with PL/SQL - Lession 09
 
Pl-sql blocks and block types and variablesdeclaring.pptx
Pl-sql blocks and block types and variablesdeclaring.pptxPl-sql blocks and block types and variablesdeclaring.pptx
Pl-sql blocks and block types and variablesdeclaring.pptx
 
Pl sql guide
Pl sql guidePl sql guide
Pl sql guide
 
PLSQL Tutorial
PLSQL TutorialPLSQL Tutorial
PLSQL Tutorial
 
PL/SQL Fundamentals I
PL/SQL Fundamentals IPL/SQL Fundamentals I
PL/SQL Fundamentals I
 
Programming in Oracle with PL/SQL
Programming in Oracle with PL/SQLProgramming in Oracle with PL/SQL
Programming in Oracle with PL/SQL
 
Plsql programs
Plsql programsPlsql programs
Plsql programs
 
Cursors
CursorsCursors
Cursors
 
PL SQL Quiz | PL SQL Examples
PL SQL Quiz |  PL SQL ExamplesPL SQL Quiz |  PL SQL Examples
PL SQL Quiz | PL SQL Examples
 

Recently uploaded

Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 

Recently uploaded (20)

Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 

PL-SQL.pdf

  • 1.
  • 2. Inroduction to PL/SQL 1 PL/SQL BLOCK 2 Conditional statements 4 Data type and Variables 3 Loop statements 5 CONTENTS PL/SQL CURSOR 6 PL/SQL Procedure/Function 7 I mplicit Cursors E xplicit Cursors 8 References
  • 3. PL/SQL (procedural language extensions to the Structured Query Language) that allows developers to combine the power of SQL with procedural statements. It allows writing a piece of code, including the SQL query in a block (which is the basic unit of it). It is a high standard and readable language, so it is very easy to understand and learn. It provides the facility to developers to use loops, conditions, object- oriented concepts and SQL. Before this, only one query is sent to the Oracle server, which increases the load and time. But through this, multiple SQL statements are grouped and sent in a single block or subprogram, which increases the processing speed and decreases the traffic on Oracle Server. 1. 2. 3. 4. 5. PL-SQL more...
  • 4.
  • 5. PL/SQL BLOCK It is the main part that contains all the code. The actual input contains the SQL statements and the instructions that will interact with the database. DECLARE - - (optional) /* Here you declare the variables you will use in this block */ BEGIN - - (mandatory) /* Here you define the executable statements (what the block DOES!)*/ EXCEPTION - - (optional) /* Here you define the actions that take place if an exception is thrown during the run of this block */ END; - - (mandatory)
  • 6. SELECT, INSERT, UPDATE, DELETE are supported. The SELECT statement has a special form in which a single tuple is placed in variables Data definition statements like CREATE, DROP, or ALTER are not allowed. PL/SQL is not case sensitive. DECLARE l_emp_name varchar(20); BEGIN SELECT fname INTO l_emp_name FROM emp WHERE ssn= 123456789; dbms_output.put_line( l_emp_name ); END; EXECUTABLE SECTION
  • 7. DATA TYPE AND VARIABLES Use of Data-Types <variable-name> <datatype> [not null][: =<initial-value>]; <constant-name> constant <datatype> : = <value>; Number – used to store any number Char - is a fixed-length data type that contains a constant number of characters. Varchar2 - is a variable-length data type that does not contain a constant number of characters. Date – used to store dates. The most common data types : more...
  • 8. Radius: 9.5 Diameter: 19 Circumference: 59.69 Area: 283.53 DECLARE pi constant number := 3.141592654; radius number(5,2); dia number(5,2); circumference number(7, 2); area number (10, 2); BEGIN radius := 9.5; dia := radius * 2; circumference := 2.0 * pi * radius; area := pi * radius * radius; dbms_output.put_line('Radius: ' || radius); dbms_output.put_line('Diameter: ' || dia); dbms_output.put_line('Circumference: ' || circumference); dbms_output.put_line('Area: ' || area); END; A Simple Program to Calculate the Circumference and Area of a Circle OUTPUT
  • 9. DATA TYPE AND VARIABLES Anchored Data Type <variable-name> <object>%type [not null][: =<initial-value>]; This another data type could be a column in the database, thereby providing the ability to match the data types of PL/SQL variables with the data types of columns defined in the database. <variable-name> <object>%rowtype [not null][: =<initial-value>]; %TYPE: is used to refer to a previously declared type which is given to an attribute of a table or a variable. %ROWTYPE: returns the record type corresponding to the type of the rows of a table or a cursor.
  • 10. DECLARE num number :=10; x num%type := 20; name employee.fname%type := 'Ahmad'; P1 project%rowtype; BEGIN dbms_output.put_line('num: ' || num); dbms_output.put_line('x: ' || x); dbms_output.put_line('name: ' || name); SELECT Pname , Plocation INTO P1.pname , P1.plocation FROM project WHERE Pnumber=10; dbms_output.put_line('P1.Name: ' || P1.pname || CHR(10) || 'P1.Plocation: ' || P1.Plocation); - - CHR(10) --->> New line EXCEPTION WHEN NO_DATA_FOUND THEN dbms_output.put_line(SQLERRM); WHEN TOO_MANY_ROWS THEN dbms_output.put_line(SQLERRM); END; num: 10 x: 20 name: Ahmad P1.Name: Computerization P1.pLocation: Stafford OUTPUT Example
  • 11. Some PL / SQL - operators
  • 12. PL/SQL If Syntax: (IF-THEN-ELSE statement): IF condition THEN {...statements to execute when condition is TRUE...} ELSE {...statements to execute when condition is FALSE...} END IF; DECLARE emp_salary number:= :EnterSalary; -- Input from the user Increment number := 0; BEGIN IF emp_salary>1000 THEN Increment :=emp_salary * 10/100; ELSE Increment :=emp_salary * 5/100; END IF; dbms_output.put_line('The salary after the increase is ' || (Increment+emp_salary)); END;
  • 13. Syntax (IF-THEN-ELSIF-ELSE) : DECLARE grade char(1) := :EnterGrade; BEGIN IF gr ade = 'A' THEN dbms_output.put_line('Excellent'); ELSIF gr ade = 'B' THEN dbms_output.put_ line('Very good'); ELSIF gr ade = 'C' THEN dbms_output.put_ line('Good'); ELSIF gr ade = 'D' THEN dbms_output.put_ line('Fair'); ELSE dbms_ou tput.put_ line('Fail'); END IF; END; IF condition 1 THEN {...statements to execute when condition1 is TRUE...} ELSIF condition2 THEN {...statements to execute when condition2 is TRUE...} ELSE {...statements to execute when if all of the previous . conditions are false...} END IF; PL/SQL If
  • 14. PL/SQL Case Statement Syntax for the CASE statement:DECLARE dayOfWeek char(1) ; BEGIN SELECT TO_CHAR(SYSDATE, 'D') INTO dayOfWeek FROM DUAL; CASE day OfWeek WHEN 1 THEN dbms_output.put_line('Today is Sunday'); WHEN 2 THEN dbms _output.put_line('Today is Monday'); WHEN 3 THEN dbms _output.put_line('Today is Tuesday'); WHEN 4 THEN dbms _output.put_line('Today is Wednesday'); WHEN 5 THEN dbms _output.put_line('Today is Thursday'); WHEN 6 THEN dbms _output.put_line('Today is Friday'); WHEN 7 THEN dbms _output.put_line('Today is Saturday'); ELSE dbms_ou tput.put_ line('Error'); END CASE; END; CASE (Expression) WHEN condition_1 TH EN result_1 WHEN condition_2 TH EN result_3 WHEN condition_3 TH EN resu lt_3 ELSE result END CASE;
  • 15. PL/SQL Case Statement Another Use Of CASE SELECT Fname,Lname,salary, CASE WHEN salary >= 5000 THEN 'High Salary' WHEN salary >= 3000 THEN 'Medium Salary' ELSE 'Low Salary' END AS SALARY_CATEGORY FROM Employee; SELECT fname,lname, CASE WHEN age >= 60 AND SEX = 'M' THEN 'Elderly Male' WHEN age >= 60 AND SEX = 'F' THEN 'Elderly Female ' WHEN age < 60 AND SEX = 'M' THEN 'Senior Male' WHEN age < 60 AND SEX = 'F' THEN 'Senior Female' ELSE 'Unknown' END as age_gender FROM employee;
  • 16. PL/SQL Exit Loop (Basic Loop) Syntax of exit loop: DECLARE sumn number := 0 ; counter number := 1; BEGIN LOOP sumn := sumn + counter; counter := counter + 1; IF counter > 10 THEN EXIT; END IF; END LOOP; dbms _output.put_line('The sum is :' || sumn); END; LOOP statements; EXIT; {or EXIT WHEN condition;} END LOOP; The sum is : 55 OUTPUT
  • 17. PL/SQL While Loop Syntax of while loop: - - Calculating even numbers between 1 and 100 DECLARE counter number := 1 ; sumn number := 0; BEGIN WHILE counter <= 100 LOOP IF counter MOD 2 = 0 THEN sumn := sumn + counter; END I F; counter := counter + 1; END LOOP; dbms _output.put_line('The sum is:' || sumn); END; WHILE <condition>; LOOP statements; END LOOP; The sum is : 2550 OUTPUT
  • 18. PL/SQL FOR Loop Syntax of for loop: - - Prints a multiplication table for numbers from 1 to 5 DECLARE result number := 0 ; BEGIN FOR i IN 1 .. 5 LOOP FOR y IN 1 .. 10 LOOP result := i * y; dbms _output. put_line(i || ' x ' ||y || ' = ' || result); END LOOP; END LOO P; END; FOR counter IN initial .. final LOOP LOOP statements; END LOOP;
  • 19. PL/SQL Cursor PL/SQL cursor is a pointer that points to a result of a query. It contains information on a select statement and the rows of data accessed by it. A cursor is used to fetch and process the rows returned by the SQL statement, one at a time. There are two types of cursors: explicit and implicit.
  • 20. PL/SQL Cursor 1) PL/SQL Implicit Cursors The implicit cursors are automatically generated by Oracle while an SQL statement is executed, if you don't use an explicit cursor for the statement. These are created by default to process the statements when DML statements like INSERT, UPDATE, DELETE etc. are executed.
  • 21. PL/SQL Cursor The following table specifies the status of the cursor with each of its attribute.
  • 22. PL/SQL Cursor DECLARE total_rows number(2); BEGIN UPDATE employee SET salary = salary + 1000 WHERE salary <= 3000; IF SQL%NOTFOUND THEN dbms_output.put_line('no customers updated'); ELSIF SQL%FOUND THEN total_rows := SQL%ROWCOUNT; dbms_output.put_line( total_rows || ' customers updated '); END IF; END; Example on Implicit Cursors:
  • 23. CLOSE EMPTY? DECLARE OPEN FETCH NO YES PL/SQL Cursor 2) PL/SQL Explicit Cursors The Explicit cursors are defined by the programmers to gain more control over the context area. These cursors should be defined in the declaration section of the PL/SQL block. It is created on a SELECT statement which returns more than one row.
  • 25. PL/SQL Cursor Example on Explicit Cursors: DECLARE ssn_var employee.ssn%type; name_var employee.fname%type; addr_var employee.address%type; CURSOR M_employee IS SELECT ssn, fname, address FROM employee WHERE sex='M'; BEGIN OPEN M_employee; LOOP FETCH M_employee INTO ssn_var, name_var, addr_var; EXIT WHEN M_employee%notfound; dbms_output.put_line(ssn_var || ' ' || name_var || ' ' || addr_var); END LOOP; CLOSE M_employee; END;
  • 26. PL/SQL Procedure The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs one or more specific tasks. It is just like procedures in other programming languages. IN parameters: These can be referenced by the procedure or function, but their values cannot be overwritten. OUT parameters: These cannot be referenced by the procedure or function, but their values can be overwritten. IN OUT parameters: These can be referenced by the procedure or function and their values can be overwritten. 1. 2. 3. How to pass parameters in procedure(modes of parameter):
  • 27. PL/SQL Procedure Syntax for creating Procedure: CREATE [OR REPLACE] PROCEDURE procedure_name [ (parameter1 [mode] datatype1, parameter2 [mode] datatype2, . . . ) ] IS | AS - - default of mode is IN [declaration_section] BEGIN executable_section END [procedure_name];
  • 28. PL/SQL Procedure create or replace procedure print_emp_S(p_ssn employee.superssn%type) IS CURSOR info_E IS SELECT fname,lname,salary FROM employee WHERE superssn = p_ssn; BEGIN FOR i IN info_E LOOP dbms_output.put_line(i.fname || i.lname || i.salary); END LOOP; END; Example on Procedure :
  • 29. Exercise PL/SQL Procedure Write PL/SQL code to update the commission value for all the employees working in a specific department according to the following formulas: 1- if the Employee department is 'Administration', let the commission to be 10% of the salary value. 2-if the Employee department is 'Headquarters', let the commission to be 5 % of the salary value. 3-otherwise, let it 2 % of the salary value.
  • 30. Solution create or replace procedure up_sal IS CURSOR cu_get_emp_d IS select salary , Dname ,ssn from employee e JOIN department d ON e.Dno = d.Dnumber; salComm_var number; BEGIN FOR var IN cu_get_emp_d LOOP IF var.Dname= 'Administration' THEN salComm_var := var.salary * 0.10; ELSIF var.Dname= 'Headquarters' THEN salComm_var := var.salary * 0.05; ELSE salComm_var := var.salary * 0.02; END IF; update employee set salary = salary + salComm_var where ssn = var.ssn ; END LOOP; END ; PL/SQL Procedure
  • 31. PL/SQL Function CREATE [OR REPLACE] FUNCTION Function_name [ (parameter1 [mode] datatype1, parameter2 [mode] datatype2, . . . ) ] RETURN data_type IS | AS - - default of mode is IN [declaration_section] BEGIN executable_section RETURN value END [function_name]; Syntax for creating Function:
  • 32. PL/SQL Function Example on Function: create or replace function customerOfCategory (T_P IN number)return varchar IS c_BRONZE_RATING number(4) := 200; c_SILVER_RATING number(4) := 500; BEGIN IF T_P <= c_BRONZE_RATING THEN return 'The customer is a BRONZE'; ELSIF T_P <= c_SILVER_RATING THEN return 'The customer is a SILVER'; ELSE return 'The customer is a GOLD'; END IF; END; DECLARE -- Input from the user total number(4) := :Enter_Total_purchases; get varchar(50); BEGIN get := customerOf Category(total); dbms_output.put_line(get); EXCEPTION WHEN VALUE_ERROR THEN dbms_output.put_line('An error occurred: ' || SQLERRM); END;