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

نسخة Ch3-Procedural Language SQL - Copy-last

Uploaded by

NAJLAA ALSAADAN
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

نسخة Ch3-Procedural Language SQL - Copy-last

Uploaded by

NAJLAA ALSAADAN
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 45

‫المملكة العربية السعودية‬

‫وزارة التعليم‬
‫جامعة االمام محمد بن سعود اإلسالمية‬
‫الكلية التطبيقية‬

‫‪Database programming‬‬
‫‪Prepared by : Marwan Ali‬‬

‫‪Chapter 3: Introduction to PL/SQL‬‬


 Contents
 Definition
 Features of PL/SQL
 Components of PL/SQL
 PL/SQL Block Structure
 Variables
 Type% attribute
 Rowtype% attribute
 Functions and Procedures
 Comments
 Single row function
 Conversion functions
 PL/SQL Nested Block
 PL/SQL Create
 Pl/SQL insert
 Pl/SQL select
 Pl/SQL update
Definition

 PL/SQL (Procedural Language/Structured Query Language) is a


powerful procedural extension to SQL that combines the data
manipulation power of SQL with the processing power of
procedural languages.

 It is a block-structured language that enables developers to


create reusable code for data manipulation, transaction
control, and error handling.
 PL/SQLis not a standalone programming
language; it is a tool within the Oracle
programming environment.
PL/SQL features

 PL/SQL (Procedural Language/Structured Query


Language) is a powerful and feature-rich
programming language designed for Oracle
database development.
 Here are some key features of PL/SQL:
PL/SQL features

1. Procedural Capabilities:
 PL/SQL extends SQL by adding procedural constructs such as conditional
statements, loops, and exception handling, allowing developers to write more
complex and structured programs.

2. Block Structure:
 PL/SQL programs are organized into blocks, which can include declarations,
executable statements, and exception handlers. The block structure makes it
easy to manage and structure code.
PL/SQL features

3. Variables and Data Types:


 PL/SQL supports a wide range of data types, including scalar types
(VARCHAR2, NUMBER, DATE) and composite types (record, table, and
associative array). Variables are used to store and manipulate data within
PL/SQL programs.

4. Control Structures:
 PL/SQL includes standard control structures such as IF-THEN-ELSE
statements, CASE statements, and various loop constructs (FOR, WHILE,
and LOOP).
PL/SQL features

5. Exception Handling:
4. PL/SQL provides a robust exception handling mechanism to deal with errors and unexpected
events. Developers can define exception handlers to gracefully manage errors and ensure the
integrity of the application.

6. Stored Procedures and Functions:


4. PL/SQL allows the creation of stored procedures and functions, which are reusable blocks of
code stored in the database. This promotes code modularization and improves
maintainability.
PL/SQL features

7. Packages:
 Packages in PL/SQL enable the encapsulation of related procedures, functions, and
variables into a single unit. This helps in organizing and managing code in a more
structured manner.

8. Triggers:
 Triggers are special types of stored procedures that automatically execute in
response to specific events, such as INSERT, UPDATE, or DELETE
operations on a table. Triggers are useful for enforcing business rules and
maintaining data integrity.

9. Dynamic SQL:
 PL/SQL supports dynamic SQL, allowing developers to construct and
execute SQL statements dynamically at runtime. This feature
PL/SQL features

10. Cursor Management:


PL/SQL provides explicit and implicit cursors for
processing query results. Cursors enable developers to
iterate through result sets and process data row by row.

11. Collections:
o PL/SQL supports collections, including associative
arrays, nested tables, and VARRAYs. Collections
provide a convenient way to work with sets of data.
PL/SQL features

12. Security:
o PL/SQL provides security features, such as privileges and roles,
to control access to database objects and ensure data security.

13.Integration with SQL:


o PL/SQL seamlessly integrates with SQL, allowing developers to
embed SQL statements directly within PL/SQL code. This tight
integration simplifies database interactions.
PL/SQL features of

 PL/SQLis also a portable language, which


means that PL/SQL code can be executed
on any database platform that supports
PL/SQL.
 Thisincludes Oracle Database, MySQL,
PostgreSQL, and SQL Server.
Components of PL/SQL
 Blocks: The fundamental units of PL/SQL code, consisting of declarations,
executable statements, and exception handlers.
 Variables: Storage locations used to store data temporarily during the execution of
a PL/SQL block.
 Constants: Values that do not change during program execution.
 Data Types: Define the type of data that can be stored in variables and constants.

 Control Structures: Conditional and iterative statements for controlling the flow of
program execution.
 Cursors: Enable the processing of result sets returned by SQL queries.

 Exceptions: Allow handling of errors and abnormal conditions.


PL/SQL Block Structure

Declare (optional)
• Variables, cursor ,user-defined exceptions

Begin (Mandotary)
• SQL statements
• PL/SQL statements

Exception(optional)
• Action to perform when error occurred

End; (Mandotary)
/
example
Block Types

 The programming pieces in PL/SQL are divided into two parts


 1. Anonymous Block: This unit does not have a specific name and is not stored
in the database, but is loaded into memory and used when needed.
 2. Named Block: Sometimes called Subprogram, these are the programming
units that have a specific name when defined and include: Function,
Procedure, Trigger Package.
Block Types
:Variables

 The declaration is done in the declaration section of a


PL/SQL block.
 PL/SQL allows you to declare and use variables.
 Variables can store data for later use in your procedures
or functions.
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 word.
:Variables
 PL/SQL supports various data types for variables,
including:
1- Scalar Types:
DECLARE

v_name VARCHAR2(50);
v_age NUMBER; VARCHAR2: Variable-length character string.
v_birthdate DATE;
v_is_adult BOOLEAN := TRUE; -- Initialization NUMBER: Numeric data type.

BEGIN -- Your code here DATE: Date and time data type.

END; BOOLEAN: Logical data type (TRUE or FALSE).


:Variable Declaration
 identifier [CONSTANT] datatype [NOT NULL];
 Identifier: Variable name
 Constant: A “constant variable” is an identifier that is similar to a variable except that it holds
one value for its entire existence (the value cannot change)
 Datatype: data type that can be stored in the variable
 Not null: A variable must contain a value and when defined it must be assigned an initial value.
 Example:
Declare
V_name VARCHAR2(10);
V_date DATE;
V_id NUMBER(2) NOT NULL:=10;
C_comm CONSTANT NUMBER:=120;
BEGIN -- your code here
END;
/
Variable assignment


You can assign values to variables using the := assignment operation
DECLARE
v_name VARCHAR2(50);
BEGIN
v_name:=‘John Doe’; -- Assigning a value to the variable
-- your code here
END;
/
:Variables

2- Composite Types:

-Record : composite data type that can hold multiple fields.

-Table : collection of elements of the same data type

-Array : varying-size array type


:Type% attribute

 Type%: The %Type datatype is use to define the variable as column name datatype for
specified table
 For example, assume there is a column named title in a table named books.
To declare a variable named my_title that has the same datatype as column
title, use dot notation and the %TYPE attribute, as follows:
 my_title books.title%TYPE;
Example: display employee name, job, salary from
emp table where employee number = 7782
using %type
Rowtype% attribute

 Rowtype%:
 In PL/SQL, records are used to group data. A record consists of a number of
related fields in which data values can be stored. The %ROWTYPE attribute
provides a record type that represents a row in a table. The record can store
an entire row of data selected from the table
 pl/sql code to display employee name, job, salary from emp table where
employee number = 7782
Example: display employee name, job, salary from emp table where employee number =
7782
using %rowtype

1- declare x variable take the same data type from employee table (emp)
2- in line 8 When printing a sentence with a value: variable name then (.)
then column name in the table:
DBMS_OUTPUT_LINE('Name' || x.ename);
Print statement in pl/sql

 DBMS_OUTPUT.PUT_LINE( )
 write what you want to print in parentheses
 Example:
 1- DBMS_OUTPUT.PUT_LINE(‘Eman’); output: Eman
 2- DBMS_OUTPUT.PUT_LINE(10); output: 10
 3- x:=14
 DBMS_OUTPUT.PUT_LINE(x); output: 14
Operations in PL/SQL
A. Arithmetic Operations
• Addition (+), Subtraction (-), Multiplication (*), Division (/), Modulus (%)

B. Comparison Operations
• Equal to (=), Not equal to (<>), Greater than (>), Less than (<), Greater than
or equal to (>=), Less than or equal to (<=)

C. Logical Operations
• AND, OR, NOT
The PL/SQL Comments

 Program comments are explanatory statements that can be


included in the PL/SQL code that you write and helps
anyone reading its source code.
 All programming languages allow some form of comments.
 The PL/SQL supports single-line and multi-line comments.
All characters available inside any comment are ignored by
the PL/SQL compiler.
 The PL/SQL single-line comments start with the delimiter --
(double hyphen) and multi-line comments are enclosed by /*
and */.
Comments

DECLARE
-- variable declaration
message varchar (20) := ‘ Hello World ‘ ;
BEGIN
/*
*
*/
dbm.output.put_line(‘message’);

END
:Single row function

• Single-row functions are built-in functions and include character, numeric, date,
conversion and user-defined functions.
• All single row functions can be used in SQL or PL/SQL programs and can be used in
the SELECT, WHERE and ORDER BY clauses.
Conversion functions

 InOracle PL/SQL, you can use conversion


functions to convert data from one type to
another.
 Here are some commonly used conversion
functions:
To_number

this example convers a string to a number value using the to_number function

DECLARE
v_string_number VARCHAR2(10) := '123’;
v_numeric_number NUMBER;
BEGIN
v_numeric_number := TO_NUMBER(v_string_number);
DBMS_OUTPUT.PUT_LINE('Numeric Number: ' || v_numeric_number);
END;
/
To_date

This example converts a string to a date using the to_date function. The second argument
.specifies the format of the input string

DECLARE
v_date_string VARCHAR2(20) := '2023-01-01';
v_date_value DATE;
BEGIN v_date_value := TO_DATE(v_date_string, 'YYYY-MM-DD');
DBMS_OUTPUT.PUT_LINE('Date Value: ' || TO_CHAR(v_date_value, 'DD-MON-YYYY’));
END;
/
To_char
This example convers a numeric value to a string using the to_char function

 DECLARE
 v_numeric_value NUMBER := 123.45;
 v_string_value VARCHAR2(20);
 BEGIN
 v_string_value := TO_CHAR(v_numeric_value);
DBMS_OUTPUT.PUT_LINE('String Value: ' || v_string_value);
 END;
 /
PL/SQL Nested Block

 PL/SQL Nested Block


To nest a block means to embed one or more PL/SQL blocks inside another
PL/SQL block that provide you with a better control over program execution
and exception handling.
The use of Data Manipulation Language
within the programming modules
 Below are examples of PL/SQL statements for
creating a procedure, inserting data, selecting
data, and updating data.
PL/SQL Create
-- Create a simple PL/SQL procedure
CREATE OR REPLACE PROCEDURE add_numbers(
p_number1 NUMBER,
p_number2 NUMBER
)
IS
v_sum NUMBER;
BEGIN
-- Calculate the sum
v_sum := p_number1 + p_number2;
-- Print the result
DBMS_OUTPUT.PUT_LINE('Sum of ' || p_number1 || ' and ' || p_number2 || ' is: ' || v_sum);

END add_numbers;
/
:Example
In the above example:
•The procedure is named add_numbers.
•It takes two parameters (p_number1 and P_number2) of type NUMBER.
•Inside the procedure, it calculates the sum of the two numbers and
stores it in the variable v_sum.
•It then prints the result using the DBMS_OUTPUT.PUT_LINE statement.
After creating the procedure, you can call it using a PL/SQL block:
-- Call the procedure
BEGIN
add_numbers(10, 20);
END;
/
PL/SQL Insert into
 -- Create a simple PL/SQL procedure for inserting an employee without commit
 CREATE OR REPLACE PROCEDURE insert_employee (
 p_employee_id NUMBER,
 p_first_name VARCHAR2,
 p_last_name VARCHAR2,
 p_salary NUMBER
 )
 IS
 BEGIN
 -- Insert the new employee record
 INSERT INTO employees(employee_id, first_name, last_name, salary)
 VALUES (p_employee_id, p_first_name, p_last_name, p_salary);
DBMS_OUTPUT.PUT_LINE('Employee inserted successfully without commit.’);
 END insert_employee;
 /
Selection

 In the above example You can use a cursor to fetch data in


PL/SQL:
 This PL/SQL block selects employees with a salary greater
than 60,000 using a cursor.
Update

DECLARE
v_employee_id NUMBER := 2;
v_new_salary NUMBER := 72000;
BEGIN
update_employee_salary(v_employee_id, v_new_salary);
END;
/
Update

This PL/SQL block calls the previously created


update_employee_salary procedure to update the salary for a
specific employee.
End of chapter 3

You might also like