0% found this document useful (0 votes)
58 views12 pages

Plsql Journal Introduction 2024

Uploaded by

darshanyt75
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views12 pages

Plsql Journal Introduction 2024

Uploaded by

darshanyt75
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

PL/SQL

PL/SQL, which stands for Procedural Language/Structured Query Language, is a powerful


programming language that is used to extend the functionality of the SQL language. It
allows you to write procedural code that can be executed on the MySQL server. PL/SQL
combines the power of SQL with the flexibility of a procedural language, making it a
valuable tool for database developers.
Advantages of PL/SQL
There are several advantages to using PL/SQL in MySQL:
1. Modularity/ Block Structures : PL/SQL allows you to break down complex tasks
into smaller, more manageable units called procedures, functions, and packages.
This modular approach makes code easier to read, understand, and maintain.
2. Performance: PL/SQL code is executed on the server side, which reduces
network traffic and improves performance. By executing multiple SQL
statements in a single PL/SQL block, you can minimize the overhead of network
round trips.
3. Error Handling: PL/SQL provides robust error handling capabilities. You can catch
and handle exceptions, ensuring that your code gracefully handles unexpected
situations. This helps in building more robust and reliable applications.
4. Security: PL/SQL allows you to encapsulate sensitive business logic within the
database, providing an additional layer of security. By granting appropriate
privileges to users, you can control access to the PL/SQL code and ensure data
integrity.

The PL/SQL Literals


A literal is an explicit numeric, character, string, or Boolean value not represented by an
identifier. PL/SQL, literals are case-sensitive. PL/SQL supports the following kinds of
literals −
 Numeric Literals
 Character Literals
 String Literals
 BOOLEAN Literals
 Date and Time Literals
The following table provides examples from all these categories of literal values.
S.No Literal Type & Example
1 Numeric Literals: example 050 78 -14 0 +32767
6.6667 0.0 -12.0 3.14159 +7800.00
6E5 1.0E-8 3.14159e0 -1E38 -9.5e-3
2 Character Literals
'A' '%' '9' ' ' 'z' '('
3 String Literals
'Hello, world!'
'19-NOV-12'
4 BOOLEAN Literals
TRUE, FALSE, and NULL.
5 Date and Time Literals
DATE '1978-12-25';
TIMESTAMP '2012-10-29 12:01:01';
Architecture of PL/SQL :The PL/SQL architecture mainly consists of following three
components:
1. PL/SQL block
2. PL/SQL Engine
3. Database Server

1. PL/SQL block: This is the component which has the actual PL/SQL code.This
consists of different sections to divide the code logically (declarative section
for declaring purpose, execution section for processing statements, exception
handling section for handling errors). It also contains the SQL instruction that
used to interact with the database server.
All the PL/SQL units are treated as PL/SQL blocks, and this is the starting stage of the
architecture which serves as the primary input.
Following are the different type of PL/SQL units.
Anonymous Block and Named Block--Function, Library, Procedure, Package Body,
Package Specification, Trigger, Type, Type Body
2. PL/SQL Engine:

 PL/SQL engine is the component where the actual processing of the codes takes
place.
 PL/SQL engine separates PL/SQL units and SQL part in the input The separated
PL/SQL units will be handled by the PL/SQL engine itself. The SQL part will be
sent to database server where the actual interaction with database takes place.
It can be installed in both database server and in the application server.
3. Database Server:
 This is the most important component of PL/SQL unit which stores the data.
 The PL/SQL engine uses the SQL from PL/SQL units to interact with the database
server.
 It consists of SQL executor which parses the input SQL statements and execute the
same.
Structure of PL/SQL Block:
The basic unit in PL/SQL is a block. All PL/SQL programs are made up of blocks,
which can be nested within each other. Blocks contain both PL/SQL as well as SQL
instruction. All these instruction will be executed as a whole rather than executing
a single instruction at a time.
. Below are different sections of PL/SQL blocks.

Typically, each block performs a logical action in the program. A block has the
following structure:

DECLARE
declaration statements;

BEGIN
executable statements

EXCEPTIONS
exception handling statements

END;
Declaration Section :This is the first section of the PL/SQL blocks. This section is an
optional part. This is the section in which the declaration of variables, cursors,
exceptions, subprograms, that are needed in the block will be
declared.Declaration section starts with DECLARE keyword
Execution Section: Execution part is the main and mandatory part which actually
executes the code that is written inside it. Since the PL/SQL expects the executable
statements from this block this cannot be an empty block, i.e., it should have at
least one valid executable code line in it. Below are few more characteristics of
this part.
 This can contain both PL/SQL code and SQL code.
 This can contain one or many blocks inside it as a nested block.
 This section starts with the keyword 'BEGIN'.
 This section should be followed either by 'END' or Exception-Handling

section (if present) The Keyword 'END' marks the end of PL/SQL block. 
Types of PL/SQL block: PL/SQL blocks are of mainly two types.
PL/SQL, the procedural language extension for SQL, provides several block
structures that allow you to organize and control the flow of your code. These block
structures include the following:
1. Anonymous Blocks:
o Anonymous blocks are sections of code that do not have a name and are
executed directly.
o They are typically used for ad-hoc or one-time operations.
o Anonymous blocks begin with the keyword BEGIN and end with the keyword
END;.
o Here's an example of an anonymous block that displays a message:
synatax:-
DECLARE
-- variable
declarations BEGIN
-- executable
statements END;
2. Named Blocks: These are named PL/SQL blocks that can be stored in the
database and executed later. Named blocks are typically used for reusable code
or stored procedures. They follow the same structure as anonymous blocks but
have a name that can be referenced for execution.
These blocks can be called from other blocks.
The block structure is same as an anonymous block, except it will never start with
the keyword 'DECLARE'. Instead, it will start with the keyword 'CREATE' which
instruct the compiler to create it as a database object.
These blocks can be nested within other blocks. It can also contain nested blocks

Example:
CREATE OR REPLACE PROCEDURE
my_procedure AS BEGIN
-- executable
statements END
my_procedure;

1. Stored Procedures
A procedure (often called a stored procedure) is a collection of
pre-compiled SQL statements stored inside the database. It is a
subroutine or a subprogram in the regular computing language. A
procedure always contains a name, parameter lists, and SQL
statements.
Stored Procedure Features
o Stored Procedure increases the performance of the applications.
o Stored procedure reduces the traffic between application and database server..
o Stored procedures are reusable and transparent to any applications.
o A procedure is always secure. The database administrator can grant
permissions to applications that access stored procedures in the database
without giving any permissions on the database tables.
How to create a procedure?
The following syntax is used for creating a stored procedure in MySQL. It can return
one or more value through parameters or sometimes may not return at all. By
default, a procedure is associated with our current database. But we can also create
it into another database from the current database by specifying the name as
database_name.procedure_name.
syntax:
1. DELIMITER &&
2. CREATE PROCEDURE procedure_name [[IN | OUT | INOUT] parameter_name datatype [, parameter
datatype]) ]
3. BEGIN
4. Declaration_section
5. Executable_section
6. END &&
7. DELIMITER ;
Parameter Explanations
The procedure syntax has the following parameters:

Parameter Name Descriptions

procedure_name It represents the name of the stored procedure.

parameter It represents the number of parameters. It can be one or more


than one.
Declaration_section It represents the declarations of all variables.

Executable_section It represents the code for the function execution.

MySQL procedure parameter has one of three modes:


IN parameter
It is the default mode. It takes a parameter as input, such as an attribute. When we define it, the
calling program has to pass an argument to the stored procedure. This parameter's value is always
protected.
mysql> delimiter //
mysql> create procedure getemp(in vlempid int)
-> begin
-> select * from employee where empid=vlempid;
-> end;
-> end//
Query OK, 0 rows affected (0.01 sec)

mysql> delimiter ;
mysql> call
getemp(101);
+-------+-------+------+--------+--------+------------
| empid | ename | age | salary | deptno |
+-------+-------+------+--------+--------+------------
| 101 | varun | 23 | 10000 | 1 |
+-------+-------+------+--------+--------+-------------
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.01 sec)


OUT parameters
It is used to pass a parameter as output. Its value can be changed inside the stored procedure, and
the changed (new) value is passed back to the calling program. It is noted that a procedure cannot
access the OUT parameter's initial value when it starts.
mysql> delimiter //
mysql> create procedure getsal(in vempid int, out vsalary int)
-> begin
-> select salary into vsalary from employee where empid=vempid;
-> end;
-> end//
Query OK, 0 rows affected (0.00
sec) mysql> delimiter ;
mysql> call
getsal(101,@vsalary); Query
OK, 0 rows affected (0.00 sec)

mysql> select @vsalary;


+ ------- +
| @vsalary |
+ ------- +
| 10000 |
+ ------- +
1 row in set (0.00 sec)

INOUT parameters
It is a combination of IN and OUT parameters. It means the calling program can pass the argument,
and the procedure can modify the INOUT parameter, and then passes the new value back to the
calling program.

The INOUT parameter example


The following example demonstrates how to use an INOUT parameter in a stored
procedure: DELIMITER $$
CREATE PROCEDURE
SetCounter( INOUT
counter INT,
IN inc INT
)
BEGI
N
SET counter = counter +
inc; END$$
DELIMITER ;

In this example, the stored procedure SetCounter() accepts one INOUT parameter ( counter )
and one IN parameter ( inc ). It increases the counter ( counter ) by the value specified by the
inc parameter.
These statements illustrate how to call the Setcounter stored procedure:
SET @counter = 1;
CALL
SetCounter(@counter,1); --
2 CALL
SetCounter(@counter,1); --
3 CALL
SetCounter(@counter,5); --
8 SELECT @counter; -- 8

Here is the output:

How to call a stored procedure?


The CALL statement to call a stored procedure. This statement returns the values to its caller through its parameters (IN,
OUT, or INOUT).

The following syntax is used to call the stored procedure

in MySQL: CALL procedure_name ( parameter(s))


------------------------------------------------ -------------------------------------------- ----

2.Functions

Functions are similar to stored procedures but return a value. They can be used in SQL
statements or other PL/SQL code to perform calculations or return specific values.
Functions can have input parameters and a return type.
Syntax
CREATE OR REPLACE FUNCTION function_name (parameter1 datatype,
parameter2 datatype) RETURN return_type
IS
-- local variable
declarations BEGIN
-- code statements
here RETURN
return_value; END;

Parameter:
Function_name: name of the function
Parameter: number of parameter. It can be one or
more than one. return_datatype: return value
datatype of the function declaration_section: all
variables are declared. executable_section: code for
the function is written here
A deterministic : function always returns the same result for the same input parameters, while a non-deterministic
function produces different results for the same input parameters.

Drop a function
In MySQL Function can also be dropped.
Syntax:
1. Drop function [ IF EXISTS ] function_name;
Parameter
function_name: name of the function to be dropped.

Despite these similarities, the CREATE FUNCTION statement differs in several


important ways:
 A stored function can return only one value, unlike a stored procedure, which can
return multiple values or an entire result set.
 A stored function supports input parameters only. A stored
procedure supports IN, OUT, and INOUT parameters in any
combination.
 A stored function must include a RETURNS clause in its definition before the
routine. The clause specifies the data type for the function’s returned value.
Stored procedures do not support this clause.
 A stored function’s routine must include a RETURN statement that specifies the
function’s returned value. The routine does not have to include any other
statements, only the RETURN statement. If it does include other statements, only
the RETURN statement can return a value.
Here's an example of a function:
CREATE FUNCTION calculate_total_salary ( p_employee_id NUMBER) RETURN
NUMBER AS v_total_salary NUMBER;
BEGIN
SELECT SUM(salary) INTO
v_total_salary FROM salaries
WHERE employee_id =
p_employee_id; RETURN
v_total_salary;
END;
---------------------------- --------------------------------------------------------------------
3.Exception Handling
Exception handling is an important aspect of programming as it allows us to
gracefully handle errors and unexpected situations that may occur during the
execution of our code.

While working with stored procedures in MySQL if an exception or occurs the


execution of the procedure terminates abruptly, to avoid this you need to handle
the exceptions in MYSQL.
MySQL provides a handler to handle the exceptions in the stored procedures. You
can handle these exceptions by declaring a handler using the MySQL DECLARE ...
HANDLER Statement.
Syntax
Following is the syntax of the MySQL HANDLER
Statement − DECLARE handler_action HANDLER
FOR condition_value
statement
The handler_action
In MySQL, there are several types of exceptions that can be encountered. Let's take a
closer look at each type and provide examples to illustrate their usage.
1. SQLSTATE Exceptions: SQLSTATE exceptions are the most common type of
exceptions in MySQL. They are identified by a five-character string that
represents a specific error condition.
For example, the SQLSTATE '23000' represents a violation of a unique
key constraint. Here's an example of how to handle a SQLSTATE
exception:
DECLARE EXIT HANDLER FOR
SQLSTATE '23000' BEGIN
-- Handle the exception here
SELECT 'Unique key constraint violation' AS
error_message; END;
2. SQLEXCEPTION: The SQLEXCEPTION exception is raised when any SQL statement
encounters an error. It can be used to handle any type of exception that is not
explicitly caught by other exception handlers.

Here's an example:
DECLARE EXIT HANDLER FOR
SQLEXCEPTION BEGIN
-- Handle the exception here
SELECT 'An error occurred' AS
error_message; END;
3. NOT FOUND: The NOT FOUND exception is raised when a SELECT INTO
statement does not find any rows to assign to variables. It can be used to
handle situations where a query does not return any results.
Here's an example:

DECLARE EXIT HANDLER FOR NOT


FOUND BEGIN
-- Handle the exception here
SELECT 'No rows found' AS
error_message; END;
4. DUP_VAL_ON_INDEX: The DUP_VAL_ON_INDEX exception is raised when a
unique or primary key constraint is violated. It can be used to handle
situations where an insert or update operation would result in a duplicate
value.

Here's an example:
DECLARE EXIT HANDLER FOR
DUP_VAL_ON_INDEX BEGIN
-- Handle the exception here
SELECT 'Duplicate value on index' AS
error_message; END;
5. TOO_MANY_ROWS: The TOO_MANY_ROWS exception is raised when a SELECT
INTO statement returns more than one row. It can be used to handle situations
where a query unexpectedly returns multiple rows.

Here's an example:
DECLARE EXIT HANDLER FOR
TOO_MANY_ROWS BEGIN
-- Handle the exception here
SELECT 'Too many rows found' AS
error_message; END;

4. A cursor in MySQL
In MySQL, a cursor is a database object that allows you to retrieve and manipulate data from a result set.
It provides a way to iterate over the rows returned by a SELECT statement, enabling you to perform
operations on each row individually.
Cursors are particularly useful when you need to perform complex operations on individual rows or
when you want to process a large result set in a controlled manner.

Here is a step-by-step guide to understanding and using cursors in MySQL:


Explicit cursors in MySQL are used to retrieve and manipulate data from a result
set returned by a SELECT statement. They provide a way to iterate over the rows
of a result set and perform operations on each row individually.
Here is a step-by-step guide on how to use explicit cursors in MySQL:
1. Declare a cursor: To use an explicit cursor, you first need to declare it. The
declaration includes the cursor name, the SELECT statement that defines the
result set, and any parameters that need to be passed to the SELECT
statement.
For example:
DECLARE cursor_name CURSOR FOR SELECT column1, column2 FROM
table_name WHERE condition;
2. Open the cursor: After declaring the cursor, you need to open it before you can
start fetching rows from the result set. Opening the cursor initializes the result
set and makes it ready for fetching. To open the cursor, use the OPEN statement.
For example:
OPEN
cursor_name;
3. Fetch rows: Once the cursor is open, you can fetch rows from the result set one
by one. The FETCH statement is used to retrieve the next row from the result set
and assign its values to variables. You can use the FETCH statement in a loop to
iterate over all the rows in the result set.
For example:
FETCH cursor_name INTO variable1, variable2;
4. Process the fetched row: After fetching a row, you can perform operations on
the retrieved values. You can use the fetched values in calculations,
comparisons, or any other operations as needed.
For example:
IF variable1 > 10 THEN
-- Perform some
operation END IF;
5. Close the cursor: Once you have finished fetching and processing all the rows,
you should close the cursor to release the resources associated with it. Closing
the cursor is done using the CLOSE statement. For example:
CLOSE cursor_name;

To declare a NOT FOUND handler, you use the following syntax:


DECLARE CONTINUE HANDLERFORNOTFOUNDSET finished = 1;
The finished is a variable to indicate that the cursor has reached the end of the
result set. Notice that the handler declaration must appear after variable and cursor
declaration inside the stored procedures.

Deallocate the cursor: After closing the cursor, you should deallocate it to free up
the memory used by the cursor. Deallocating the cursor is done using the
DEALLOCATE statement. For example:
DEALLOCATE cursor_name;

Implicit cursors
In MySQL, a cursor is a database object that allows you to retrieve and manipulate
data from a result set. There are two types of cursors: explicit and implicit. In this
answer, we will focus on implicit cursors.
An implicit cursor is automatically created by MySQL when you execute a SELECT
statement. It is used to retrieve the result set generated by the SELECT statement.
Unlike explicit cursors, you do not need to explicitly declare or manage an implicit
cursor.
*************************** ******** ********************************

You might also like