SlideShare a Scribd company logo
1 of 42
PL/SQL
Block , Declaring variables ,Flow of Control and Exception Handling
Part 1
About PL/SQL
• PL/SQL: Stands for “Procedural Language” extension to SQL.
• Is Oracle Corporation's standard data access language for relational
databases
• Seamlessly integrates procedural constructs with SQL
About PL/SQL
• Provides a block structure for executable units of code.
Maintenance of code is made easier with such a well- defined
structure.
• Provides procedural constructs such as:
- Variables, constants, and data types
- Control structures such as conditional statements and loops
- Reusable program units that are written once and executed many
times
Benefits of PL/SQL
Benefits of PL/SQL
• Integration of procedural constructs with SQL
• Improved performance
• Exception handling
PL/SQL Block
PL/SQL Block Structure
DECLARE (optional)
- Variables, cursors, user-defined exceptions
BEGIN (mandatory)
- SQL statements
- PL/SQL statements
EXCEPTION (optional)
- Actions to perform when exceptions occur
END; (mandatory)
Block Types
• Anonymous
• Procedure
• Function
Anonymous
[Declare]
Begin
--Statements
[Exception]
End
Procedure
PROCEDUER name
IS
Begin
--Statements
[Exception]
End
Function
FUNCTION name
RETURN
Begin
--Statements
RETURN value
[Exception]
End
Examining an Anonymous Block
SET SERVEROUTPUT ON;
DECLARE
v_hello VARCHAR2(20):= 'Hello World!';
BEGIN
dbms_output.put_line(v_hello);
END;
Enabling Output of a PL/SQL Block
• To enable output in SQL Developer, execute the following command
before running the PL/SQL block:
SET SERVEROUTPUT ON;
• Use a predefined Oracle package and its procedure in the anonymous
block:
DBMS_OUTPUT.PUT_LINE();
Ex:
DBMS_OUTPUT.PUT_LINE('The First Name of the Employee is' ||
v_fname);
Declaring PL/SQL Variables
Use of Variables
Variables can be used for:
• Temporary storage of data
• Manipulation of stored values
• Reusability
Requirements for Variable Names
A variable name:
• Must start with a letter
• Can include letters or numbers
• Can include special characters (such as $,_, and #)
• Must contain no more than 30 characters
• Must not include reserved words
Declaring and Initializing PL/SQL Variables
Syntax:
1. Var_Name DataType;
2. Var_Name DataType := value;
3. Var_Name DataType Default value;
4. Var_Name DataType NOT Null =: value;
5. Var_Name CONSTANT DataType := value;
Guidelines for Declaring and Initializing
PL/SQL Variables
1. Follow consistent naming conventions.
2. Use meaningful identifiers for variables.
3. Initialize variables that are designated as NOT NULL and CONSTANT.
4. Initialize variables with the assignment operator (:) or the DEFAULT
keyword:
V_myName VARCHAR2(20):='John';
V_myName VARCHAR2 (20) DEFAULT 'John';
5.Declare one identifier per line for better readability and code maintenance.
6. Avoid using column names as identifiers.
7. Use the NOT NULL constraint when the variable must hold a value.
Declaring Variables
DECLARE
v_fname VARCHAR2(20);
BEGIN
SELECT first_name
INTO v_fname
FROM employees
WHERE employee_id = 100;
dbms_output.put_line(v_fname);
END;
/
Declaring Variables
DECLARE
v_fname VARCHAR2(20):= 'Ahmed';
BEGIN
dbms_output.put_line(v_fname);
v_fname:='Mohammed';
dbms_output.put_line(v_fname);
END;
/
---------------------------------------------------------------------------------------------------------------------
DECLARE
v_fname VARCHAR2(20) Default 'Ahmed';
BEGIN
dbms_output.put_line(v_fname);
v_fname:='Mohammed';
dbms_output.put_line(v_fname);
END;
/
Declaring Variables
DECLARE
v_fname VARCHAR2(20);
BEGIN
dbms_output.put_line(v_fname);
END;
/
---------------------------------------------------------------------------------------------------------------------
DECLARE
v_fname VARCHAR2(20) NOT NULL :='Ahmed';
BEGIN
dbms_output.put_line(v_fname);
END;
/
Declaring Variables
DECLARE
v_fname CONSTANT VARCHAR2(20) :='Ahmed';
BEGIN
dbms_output.put_line(v_fname);
END;
/
---------------------------------------------------------------------------------------------------------------------
DECLARE
v_fname CONSTANT VARCHAR2(20) :='Ahmed';
BEGIN
v_fname :='Ali';
dbms_output.put_line(v_fname);
END;
/
%TYPE Attribute
Is used to declare a variable according to:
• A database column definition
• Another declared variables
prefixed with:
• The database table and column name
• The name of the declared variable
%TYPE Attribute
Syntax:
• Variable_Name TableName.ColumnName%Type;
• Variable_Name Another_Variable_Name%Type;
%TYPE Attribute
DECLARE
v_FirstName Employees.First_Name%Type;
BEGIN
SELECT first_name
INTO v_FirstName
FROM Employees
WHERE employee_id = 100;
dbms_output.put_line(v_FirstName);
END;
%TYPE Attribute
DECLARE
V_FirstName Employees.First_Name%Type;
V_LastName V_FirstName%Type;
BEGIN
SELECT last_name
INTO V_LastName
FROM Employees
WHERE employee_id = 100;
dbms_output.put_line( V_LastName);
END;
Bind Variables
Bind variables are:
• Created in the environment
• Also called host variables
• Created with the VARIABLE keyword*
• Used in SQL statements and PL/SQL blocks
• Accessed even after the PL/SQL block is executed
• Referenced with a preceding colon
• Values can be output using the PRINT command.
Using AUTOPRINT with Bind Variables
Use the SET AUTOPRINT ON command to automatically display the
bind variables used in a successful PL/SQL block.
Bind Variables
SET AUTOPRINT ON;
VARIABLE b_result NUMBER
BEGIN
SELECT SALARY INTO :b_result
FROM employees
WHERE employee_id = 144;
END;
/
PRINT b_result
IF Statement
Simple IF Statement
IF condition THEN
Statements
End IF;
Simple IF Statement
DECLARE
v_MyNumber Number :=18;
BEGIN
IF v_MyNumber > 0
THEN
dbms_output.put_line('It is +');
End IF;
END;
/
IF THEN ELSE Statement
IF condition THEN
Statements
ELSE
Statements
End IF;
IF THEN ELSE Statement
DECLARE
v_MyNumber Number :=-18;
BEGIN
IF v_MyNumber > 0
THEN
dbms_output.put_line('It is +');
ELSE
dbms_output.put_line('It is -');
End IF;
END;
/
IF THEN ELSE Statement
IF condition THEN
Statements
ELSEIF condition THEN
Statements
ELSE
Statements
End IF;
IF THEN ELSE Statement
DECLARE
v_MyNumber NUMBER := 0;
BEGIN
IF v_MyNumber > 0 THEN
dbms_output.put_line('It is +');
ELSIF v_MyNumber < 0 THEN
dbms_output.put_line('It is -');
ELSE
dbms_output.put_line('It is Zero');
END IF;
END;
Case Statement
Case Expression
CASE
WHEN expression1 THEN result1
WHEN expression2 THEN result2
…..
[ELSE result]
END;
Case Statement
DECLARE
v_score NUMBER := 85;
v_grade VARCHAR2(2);
BEGIN
CASE
WHEN v_score >= 90 THEN
v_grade := 'A';
WHEN v_score >= 80 THEN
v_grade := 'B';
WHEN v_score >= 70 THEN
v_grade := 'C';
WHEN v_score >= 60 THEN
v_grade := 'D';
ELSE
v_grade := 'F';
END CASE;
dbms_output.put_line('Grade: ' || v_grade);
END;
/
Iterative Control
Loop Statements
Iterative Control: Loop Statements
• Loops repeat a statement (or a sequence of statements) multiple
times.
• There are three loop types:
1. Basic loop
2. WHILE loop
3. FOR loop
Basic Loops
LOOP
Statements
Exit [When condition];
END LOOP;
Basic Loops
DECLARE
v_counter NUMBER := 1;
BEGIN
LOOP
dbms_output.put_line('Iteration: ' || v_counter);
v_counter := v_counter + 1;
EXIT WHEN v_counter > 5;
END LOOP;
END;
/
Basic Loops
DECLARE
v_countryid locations.country_id%TYPE := 'CA';
v_loc_id locations.location_id%TYPE;
v_counter NUMBER(2) := 1;
v_new_city locations.city%TYPE:= 'Montreal';
BEGIN
SELECT MAX(location_id) INTO v_loc_id FROM locations
WHERE country_id= v_countryid;
LOOP
INSERT INTO locations (location_id, city, country_id) VALUES((v_loc_id + v_counter), v_new_city, v_countryid);
v_counter := v_counter + 1;
EXIT WHEN v_counter > 3;
END LOOP;
END;
/
While Loop
While Condition
LOOP
Statement1;
Statement2;
……
END LOOP;
While Loop
DECLARE
v_countryid locations.country_id%TYPE:= 'CA';
v_loc_id locations.location_id%TYPE;
v_new_city locations.city%TYPE:= 'Montreal';
v_counter NUMBER:= 1;
BEGIN
SELECT MAX(location_id) INTO v_loc_id FROM locations
WHERE country_id = v_countryid;
WHILE v_counter <= 3 LOOP
INSERT INTO locations (location_id, city, country_id)
VALUES((v_loc_id + v_counter), v_new_city, v_countryid);
v_counter := v_counter + 1;
END LOOP;
END;
/

More Related Content

Similar to Pl-sql blocks and block types and variablesdeclaring.pptx

Similar to Pl-sql blocks and block types and variablesdeclaring.pptx (20)

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
 
SQL- Introduction to PL/SQL
SQL- Introduction to  PL/SQLSQL- Introduction to  PL/SQL
SQL- Introduction to PL/SQL
 
Plsql
PlsqlPlsql
Plsql
 
PLSQL
PLSQLPLSQL
PLSQL
 
PL/SQL Fundamentals I
PL/SQL Fundamentals IPL/SQL Fundamentals I
PL/SQL Fundamentals I
 
Pl sql
Pl sqlPl sql
Pl sql
 
Pl sql
Pl sqlPl sql
Pl sql
 
Pl sql
Pl sqlPl sql
Pl sql
 
L9 l10 server side programming
L9 l10  server side programmingL9 l10  server side programming
L9 l10 server side programming
 
Plsql
PlsqlPlsql
Plsql
 
Programming in Oracle with PL/SQL
Programming in Oracle with PL/SQLProgramming in Oracle with PL/SQL
Programming in Oracle with PL/SQL
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts
 
PLSQLmy Updated (1).pptx
PLSQLmy Updated (1).pptxPLSQLmy Updated (1).pptx
PLSQLmy Updated (1).pptx
 
Meg bernal insight2014 4219
Meg bernal insight2014 4219Meg bernal insight2014 4219
Meg bernal insight2014 4219
 
SQL / PL
SQL / PLSQL / PL
SQL / PL
 
Programming-in-C
Programming-in-CProgramming-in-C
Programming-in-C
 
Pl sql
Pl sqlPl sql
Pl sql
 
PL/SQL Part 1
PL/SQL Part 1PL/SQL Part 1
PL/SQL Part 1
 
Pl sql guide
Pl sql guidePl sql guide
Pl sql guide
 
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
 

Recently uploaded

Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...amitlee9823
 
Midocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFxMidocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFxolyaivanovalion
 
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...amitlee9823
 
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 nightCheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 nightDelhi Call girls
 
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptxBPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptxMohammedJunaid861692
 
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779Delhi Call girls
 
BabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxBabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxolyaivanovalion
 
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% SecureCall me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% SecurePooja Nehwal
 
VidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptxVidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptxolyaivanovalion
 
Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfLars Albertsson
 
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
Data-Analysis for Chicago Crime Data 2023
Data-Analysis for Chicago Crime Data  2023Data-Analysis for Chicago Crime Data  2023
Data-Analysis for Chicago Crime Data 2023ymrp368
 
ALSO dropshipping via API with DroFx.pptx
ALSO dropshipping via API with DroFx.pptxALSO dropshipping via API with DroFx.pptx
ALSO dropshipping via API with DroFx.pptxolyaivanovalion
 
CebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxCebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxolyaivanovalion
 
Carero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxCarero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxolyaivanovalion
 
Call Girls 🫤 Dwarka ➡️ 9711199171 ➡️ Delhi 🫦 Two shot with one girl
Call Girls 🫤 Dwarka ➡️ 9711199171 ➡️ Delhi 🫦 Two shot with one girlCall Girls 🫤 Dwarka ➡️ 9711199171 ➡️ Delhi 🫦 Two shot with one girl
Call Girls 🫤 Dwarka ➡️ 9711199171 ➡️ Delhi 🫦 Two shot with one girlkumarajju5765
 
Vip Model Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...
Vip Model  Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...Vip Model  Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...
Vip Model Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...shivangimorya083
 

Recently uploaded (20)

Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
 
Midocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFxMidocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFx
 
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
 
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 nightCheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
 
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptxBPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
 
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
 
BabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxBabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptx
 
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% SecureCall me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
 
VidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptxVidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptx
 
Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdf
 
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
 
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
Data-Analysis for Chicago Crime Data 2023
Data-Analysis for Chicago Crime Data  2023Data-Analysis for Chicago Crime Data  2023
Data-Analysis for Chicago Crime Data 2023
 
ALSO dropshipping via API with DroFx.pptx
ALSO dropshipping via API with DroFx.pptxALSO dropshipping via API with DroFx.pptx
ALSO dropshipping via API with DroFx.pptx
 
CebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxCebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptx
 
Carero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxCarero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptx
 
Call Girls 🫤 Dwarka ➡️ 9711199171 ➡️ Delhi 🫦 Two shot with one girl
Call Girls 🫤 Dwarka ➡️ 9711199171 ➡️ Delhi 🫦 Two shot with one girlCall Girls 🫤 Dwarka ➡️ 9711199171 ➡️ Delhi 🫦 Two shot with one girl
Call Girls 🫤 Dwarka ➡️ 9711199171 ➡️ Delhi 🫦 Two shot with one girl
 
Vip Model Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...
Vip Model  Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...Vip Model  Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...
Vip Model Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...
 
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in  KishangarhDelhi 99530 vip 56974 Genuine Escort Service Call Girls in  Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
 
꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...
꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...
꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...
 

Pl-sql blocks and block types and variablesdeclaring.pptx

  • 1. PL/SQL Block , Declaring variables ,Flow of Control and Exception Handling Part 1
  • 2. About PL/SQL • PL/SQL: Stands for “Procedural Language” extension to SQL. • Is Oracle Corporation's standard data access language for relational databases • Seamlessly integrates procedural constructs with SQL
  • 3. About PL/SQL • Provides a block structure for executable units of code. Maintenance of code is made easier with such a well- defined structure. • Provides procedural constructs such as: - Variables, constants, and data types - Control structures such as conditional statements and loops - Reusable program units that are written once and executed many times
  • 4. Benefits of PL/SQL Benefits of PL/SQL • Integration of procedural constructs with SQL • Improved performance • Exception handling
  • 6. PL/SQL Block Structure DECLARE (optional) - Variables, cursors, user-defined exceptions BEGIN (mandatory) - SQL statements - PL/SQL statements EXCEPTION (optional) - Actions to perform when exceptions occur END; (mandatory)
  • 7. Block Types • Anonymous • Procedure • Function Anonymous [Declare] Begin --Statements [Exception] End Procedure PROCEDUER name IS Begin --Statements [Exception] End Function FUNCTION name RETURN Begin --Statements RETURN value [Exception] End
  • 8. Examining an Anonymous Block SET SERVEROUTPUT ON; DECLARE v_hello VARCHAR2(20):= 'Hello World!'; BEGIN dbms_output.put_line(v_hello); END;
  • 9. Enabling Output of a PL/SQL Block • To enable output in SQL Developer, execute the following command before running the PL/SQL block: SET SERVEROUTPUT ON; • Use a predefined Oracle package and its procedure in the anonymous block: DBMS_OUTPUT.PUT_LINE(); Ex: DBMS_OUTPUT.PUT_LINE('The First Name of the Employee is' || v_fname);
  • 11. Use of Variables Variables can be used for: • Temporary storage of data • Manipulation of stored values • Reusability
  • 12. Requirements for Variable Names A variable name: • Must start with a letter • Can include letters or numbers • Can include special characters (such as $,_, and #) • Must contain no more than 30 characters • Must not include reserved words
  • 13. Declaring and Initializing PL/SQL Variables Syntax: 1. Var_Name DataType; 2. Var_Name DataType := value; 3. Var_Name DataType Default value; 4. Var_Name DataType NOT Null =: value; 5. Var_Name CONSTANT DataType := value;
  • 14. Guidelines for Declaring and Initializing PL/SQL Variables 1. Follow consistent naming conventions. 2. Use meaningful identifiers for variables. 3. Initialize variables that are designated as NOT NULL and CONSTANT. 4. Initialize variables with the assignment operator (:) or the DEFAULT keyword: V_myName VARCHAR2(20):='John'; V_myName VARCHAR2 (20) DEFAULT 'John'; 5.Declare one identifier per line for better readability and code maintenance. 6. Avoid using column names as identifiers. 7. Use the NOT NULL constraint when the variable must hold a value.
  • 15. Declaring Variables DECLARE v_fname VARCHAR2(20); BEGIN SELECT first_name INTO v_fname FROM employees WHERE employee_id = 100; dbms_output.put_line(v_fname); END; /
  • 16. Declaring Variables DECLARE v_fname VARCHAR2(20):= 'Ahmed'; BEGIN dbms_output.put_line(v_fname); v_fname:='Mohammed'; dbms_output.put_line(v_fname); END; / --------------------------------------------------------------------------------------------------------------------- DECLARE v_fname VARCHAR2(20) Default 'Ahmed'; BEGIN dbms_output.put_line(v_fname); v_fname:='Mohammed'; dbms_output.put_line(v_fname); END; /
  • 18. Declaring Variables DECLARE v_fname CONSTANT VARCHAR2(20) :='Ahmed'; BEGIN dbms_output.put_line(v_fname); END; / --------------------------------------------------------------------------------------------------------------------- DECLARE v_fname CONSTANT VARCHAR2(20) :='Ahmed'; BEGIN v_fname :='Ali'; dbms_output.put_line(v_fname); END; /
  • 19. %TYPE Attribute Is used to declare a variable according to: • A database column definition • Another declared variables prefixed with: • The database table and column name • The name of the declared variable
  • 20. %TYPE Attribute Syntax: • Variable_Name TableName.ColumnName%Type; • Variable_Name Another_Variable_Name%Type;
  • 21. %TYPE Attribute DECLARE v_FirstName Employees.First_Name%Type; BEGIN SELECT first_name INTO v_FirstName FROM Employees WHERE employee_id = 100; dbms_output.put_line(v_FirstName); END;
  • 22. %TYPE Attribute DECLARE V_FirstName Employees.First_Name%Type; V_LastName V_FirstName%Type; BEGIN SELECT last_name INTO V_LastName FROM Employees WHERE employee_id = 100; dbms_output.put_line( V_LastName); END;
  • 23. Bind Variables Bind variables are: • Created in the environment • Also called host variables • Created with the VARIABLE keyword* • Used in SQL statements and PL/SQL blocks • Accessed even after the PL/SQL block is executed • Referenced with a preceding colon • Values can be output using the PRINT command.
  • 24. Using AUTOPRINT with Bind Variables Use the SET AUTOPRINT ON command to automatically display the bind variables used in a successful PL/SQL block.
  • 25. Bind Variables SET AUTOPRINT ON; VARIABLE b_result NUMBER BEGIN SELECT SALARY INTO :b_result FROM employees WHERE employee_id = 144; END; / PRINT b_result
  • 27. Simple IF Statement IF condition THEN Statements End IF;
  • 28. Simple IF Statement DECLARE v_MyNumber Number :=18; BEGIN IF v_MyNumber > 0 THEN dbms_output.put_line('It is +'); End IF; END; /
  • 29. IF THEN ELSE Statement IF condition THEN Statements ELSE Statements End IF;
  • 30. IF THEN ELSE Statement DECLARE v_MyNumber Number :=-18; BEGIN IF v_MyNumber > 0 THEN dbms_output.put_line('It is +'); ELSE dbms_output.put_line('It is -'); End IF; END; /
  • 31. IF THEN ELSE Statement IF condition THEN Statements ELSEIF condition THEN Statements ELSE Statements End IF;
  • 32. IF THEN ELSE Statement DECLARE v_MyNumber NUMBER := 0; BEGIN IF v_MyNumber > 0 THEN dbms_output.put_line('It is +'); ELSIF v_MyNumber < 0 THEN dbms_output.put_line('It is -'); ELSE dbms_output.put_line('It is Zero'); END IF; END;
  • 34. Case Expression CASE WHEN expression1 THEN result1 WHEN expression2 THEN result2 ….. [ELSE result] END;
  • 35. Case Statement DECLARE v_score NUMBER := 85; v_grade VARCHAR2(2); BEGIN CASE WHEN v_score >= 90 THEN v_grade := 'A'; WHEN v_score >= 80 THEN v_grade := 'B'; WHEN v_score >= 70 THEN v_grade := 'C'; WHEN v_score >= 60 THEN v_grade := 'D'; ELSE v_grade := 'F'; END CASE; dbms_output.put_line('Grade: ' || v_grade); END; /
  • 37. Iterative Control: Loop Statements • Loops repeat a statement (or a sequence of statements) multiple times. • There are three loop types: 1. Basic loop 2. WHILE loop 3. FOR loop
  • 38. Basic Loops LOOP Statements Exit [When condition]; END LOOP;
  • 39. Basic Loops DECLARE v_counter NUMBER := 1; BEGIN LOOP dbms_output.put_line('Iteration: ' || v_counter); v_counter := v_counter + 1; EXIT WHEN v_counter > 5; END LOOP; END; /
  • 40. Basic Loops DECLARE v_countryid locations.country_id%TYPE := 'CA'; v_loc_id locations.location_id%TYPE; v_counter NUMBER(2) := 1; v_new_city locations.city%TYPE:= 'Montreal'; BEGIN SELECT MAX(location_id) INTO v_loc_id FROM locations WHERE country_id= v_countryid; LOOP INSERT INTO locations (location_id, city, country_id) VALUES((v_loc_id + v_counter), v_new_city, v_countryid); v_counter := v_counter + 1; EXIT WHEN v_counter > 3; END LOOP; END; /
  • 42. While Loop DECLARE v_countryid locations.country_id%TYPE:= 'CA'; v_loc_id locations.location_id%TYPE; v_new_city locations.city%TYPE:= 'Montreal'; v_counter NUMBER:= 1; BEGIN SELECT MAX(location_id) INTO v_loc_id FROM locations WHERE country_id = v_countryid; WHILE v_counter <= 3 LOOP INSERT INTO locations (location_id, city, country_id) VALUES((v_loc_id + v_counter), v_new_city, v_countryid); v_counter := v_counter + 1; END LOOP; END; /