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

plsql

The document discusses the disadvantages of SQL and introduces PL/SQL, Oracle's procedural language extension to SQL, highlighting its features, advantages, and syntax. It covers various programming constructs in PL/SQL, including loops, conditional statements, and named blocks like procedures and functions. Additionally, it explains the use of cursors and exception handling in PL/SQL programming.

Uploaded by

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

plsql

The document discusses the disadvantages of SQL and introduces PL/SQL, Oracle's procedural language extension to SQL, highlighting its features, advantages, and syntax. It covers various programming constructs in PL/SQL, including loops, conditional statements, and named blocks like procedures and functions. Additionally, it explains the use of cursors and exception handling in PL/SQL programming.

Uploaded by

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

Dis Advantagers of Sql

• SQL does not have any procedural capabilities


• SQL statements are passed to the oracle engine one at a time.
• While processing an sql error occurs, the oracle engine display its own error message.

What is PL/SQL?
PL/SQL is oracle’s procedural language extension to SQL. PL/SQL allows to mix SQL statements with procedural statements.
PL/SQL is superset of SQL.
It was developed by oracle’s corporation early 90’s to enhance the capabilities.

Features of PL/SQL
• PL/SQL has the following features
• PL/SQL is tightly integrated with SQL.
• It offers extensive error checking.
• It offers numerous data types.
• It offers a variety of programming structures.
• It supports structured programming through functions and procedures.
• It supports object-oriented programming.
• It supports the development of web applications and server pages.
Advantages of PL/SQL
PL/SQL has the following advantages −
• SQL is the standard database language and PL/SQL is strongly integrated with SQL.
• PL/SQL supports both static and dynamic SQL. Static SQL supports DML operations and
transaction control from PL/SQL block. In Dynamic SQL, SQL allows embedding DDL statements
in PL/SQL blocks.
• PL/SQL allows sending an entire block of statements to the database at one time. This reduces
network traffic and provides high performance for the applications.
• PL/SQL gives high productivity to programmers as it can query, transform, and update data in a
database.
• PL/SQL saves time on design and debugging by strong features, such as exception handling,
encapsulation, data hiding, and object-oriented data types.
• Applications written in PL/SQL are fully portable.
• PL/SQL provides high security level.
• PL/SQL provides access to predefined SQL packages.
• PL/SQL provides support for Object-Oriented Programming.
• PL/SQL provides support for developing Web Applications and Server Pages.
//Simple hello world program
CREATE PROCEDURE `hello_world`()
DECLARE
message VARCHAR(20);
SET message = 'Hello, World!’;
SELECT message AS OutputMessage;
end

Assignment Operator ( := )
Assignment operator allows a value to be stored in a variable.
Syntax: variable := expression;
The following are examples of assignment operator:
count := 1;
name := ‘Srikanth’;

Displaying output from PL/SQL


In order to display output from a PL/SQL block, we have to use DBMS_OUTPUT package.
A package is a collection of procedures and functions.
PUT and PUT_LINE procedures both these procedures are used to display a NUMBER,
VARCHAR2 or DATE type value.
PUT allows you to put multiple pieces that make up a line. PUT_LINE puts the given data
followed by end-of-line character.
PL/SQL-Basic Syntax
PL/SQL programs are divided and written in logical blocks of code.
Each block consists of three sub-parts Declarations This section starts with the keyword

DECLARE.:It is an optional section and defines all variables, cursors, subprograms, and other
elements to be used in the program.
Executable Commands: This section is enclosed between the keywords BEGIN and END and it is a
mandatory section. It consists of the executable PL/SQL statements of the program. It should have
at least one executable line of code, which may be just a NULL command to indicate that nothing
should be executed.
Exception Handling: This section starts with the keyword EXCEPTION. This optional section contains
exception(s) that handle errors in the program.
DECLARE
<declaration section>
BEGIN
<Executable commands>
EXCEPTION
<exception block>
//pl/sql program for declaring and assigning values
1.CREATE PROCEDURE `declare_variables`()
BEGIN
-- Variable declarations
DECLARE my_number INT;
DECLARE my_text VARCHAR(255);
DECLARE my_date DATE;
-- Your PL/SQL logic goes here
-- You can use and manipulate the declared variables within this block
SET my_number := 42; -- Assign a value to the variable
SET my_text := 'Hello, PL/SQL!';
SET my_date := CURRENT_DATE; -- Use CURRENT_DATE instead of SYSDATE in MySQL
-- Output the values (you can use SELECT or other methods in MySQL)
SELECT my_number, my_text, my_date;
END
2.CREATE PROCEDURE `declare_variables`()
BEGIN
DECLARE my_number INT DEFAULT 42;
DECLARE my_text VARCHAR(60) DEFAULT 'Hello, MySQL!';
DECLARE my_date DATE DEFAULT CURRENT_DATE;

SELECT my_number, my_text, my_date;


END

3. CREATE PROCEDURE `declare_variables`()


BEGIN
DECLARE my_number INT;
DECLARE my_text VARCHAR(90);
DECLARE my_date DATE;
SELECT 42 AS my_number,
'Hello, MySQL!' AS my_text,
CURRENT_DATE AS my_date
INTO
my_number, my_text, my_date;
SELECT my_number, my_text, my_date;
END
PL/SQL Architecture
Every PL/SQL block is first executed by PL/SQL engine.
 This is the engine that compiles and executes PL/SQL blocks.
PL/SQL engine executes all procedural statements of a PL/SQL of the block, but sends SQL command to SQL statements
executor in the Oracle RDBMS.
 That means PL/SQL separates SQL commands from PL/SQL commands and executes PL/SQL commands using
Procedural statement executor, which is a part of PL/SQL engine.
 PL/SQL engine locates both client side as well as server side also.
 All SQL statements that are embedded within the PL/SQL block sent to the oracle server.

Comments in PL/SQL
You can give comments in PL/SQL block in two ways.
 First way is by preceding the comment with two hyphens (- -).

Example: -- this is single line comment


 Second way is by starting the comment with /* and ending it with */.

Example: /* this comment can be of multiple lines */


Conditional Statements in PL/SQL

IF - THEN statement:

The IF statement associates a condition with a sequence of statements enclosed by the


keywords THEN (starting of IF) and END IF; (ending of IF).
If the condition is TRUE, the statements get executed, and if the condition is FALSE or
NULL, then the IF statement display nothing.
Syntax for IF-THEN statement is:
IF condition

THEN
Statements;
END IF;
Ex:
CREATE PROCEDURE `simple_if_example`(IN value INT)
Begin
DECLARE result_message VARCHAR(50);
IF value > 0 THEN
SET result_message = 'Value is positive';
END IF ;
SELECT result_message AS Result;
END

2.IF-THEN-ELSE statement
In this user executes true block as well as false block statements.
Syntax for the IF-THEN-ELSE statement is:
IF condition
THEN
S1;
ELSE
S2;
END IF;
Where, S1 and S2 are different sequence of statements. In the IF-THEN-ELSE statements,
when the test condition is TRUE, the statement S1 is executed and S2 is skipped; when the
test condition is FALSE, then statement S2 is executed.
Example for if then else statement
CREATE PROCEDURE `if_then_else`(IN value INT)
BEGIN DECLARE result_message VARCHAR(50);
IF value > 0 THEN
SET result_message := 'Value is positive’;
else
SET result_message := 'Value is negative’;
end if;
SELECT result_message AS Result;
END

3. IF-THEN-ELSEIF statement
When we mention 2 or more conditions on one program we use this syntax.
The syntax of an IF-THEN-ELSIF Statement in PL/SQL programming language is:
IF (condition 1) THEN
S1; -- Executes when the condition 1 is true
ELSE IF (condition 2)
THEN
S2; -- Executes when the condition 2 is true
ELSE IF (condition 3)
THEN
S3; -- Executes when the condition 3 is true
ELSE
S4; -- executes when the none of the above condition is true END IF;
Ex:
CREATE PROCEDURE `if_then_else_if`(IN value INT)
BEGIN
DECLARE result_message VARCHAR(50);
IF value > 0 THEN
SET result_message = 'Value is positive';
ELSEIF value < 0 THEN
SET result_message = 'Value is negative';
ELSE
SET result_message = 'Value is one';
END IF;
SELECT result_message AS Result;
END
Nested IF-THEN
It is always legal in PL/SQL programming to nest IF-ELSE statements, which means you can use one IF or ELSE IF
statement inside another IF or ELSE IF statement(s).
Syntax:
IF( condition 1)
THEN
IF(condition 2)
THEN
sequence-of-statements;
END IF;
END IF;
Ex:
CREATE PROCEDURE `nested_if`()
BEGIN
DECLARE a INT DEFAULT 100;
DECLARE b INT DEFAULT 200;
IF a = 100 THEN
IF b = 200 THEN
SELECT 'Value of a is 100 and b is 200' AS message;
END IF;
END IF;
END

Case statement
Like the IF statement, the CASE statement selects one sequence of statements to execute. This statement will select any one
of several alternatives.
The syntax for case statement in PL/SQL is:
CASE selector
WHEN 'value1' THEN Statement1;
WHEN 'value2' THEN Statement2;
WHEN 'value3' THEN Statement3;
...
ELSE Statement n; -- default case
END CASE;
Ex:
CREATE PROCEDURE `example_case_statement`(IN value INT)
Begin
DECLARE result_message VARCHAR(50);
CASE WHEN value > 0 THEN
SET result_message = 'Value is positive';
WHEN value < 0 THEN
SET result_message = 'Value is negative';
ELSE
SET result_message = 'Value is zero’;
END CASE;
SELECT result_message AS Result;END
Looping Control Statements
PL/SQL Basic LOOP
Basic loop structure encloses sequence of statements in between the LOOP and END LOOP statements. With each
iteration, the sequence of statements is executed and then control resumes at the top of the loop.

The syntax of a basic loop in PL/SQL programming language is:


LOOP
Sequence of statements;
END LOOP;
Here, sequence of statement(s) may be a single statement or a block of statements. An EXIT statement or an EXIT WHEN
statement is required to break the loop.
Example:
CREATE PROCEDURE `loop_ex`()
begin
DECLARE counter INT DEFAULT 1;
simple_loop: LOOP --labels are used to specify the loop to leave incase of a condition.
SELECT counter AS CurrentCounter;
SET counter = counter + 1;
IF counter > 3 THEN
LEAVE simple_loop; -- exits the loop
END IF;
END LOOP simple_loop;
END
A WHILE LOOP statement in PL/SQL programming language repeatedly executes a target statement as long as a given
condition is true.
Syntax:
WHILE condition do
sequence_of_statements
END while;

Ex:
CREATE PROCEDURE `example_while_loop`()
BEGIN
DECLARE counter INT DEFAULT 1;
WHILE counter <= 3 DO
SELECT counter AS CurrentCounter;
SET counter = counter + 1;
END WHILE;
END
Nested loops in PL/SQL
PL/SQL allows using one loop inside another loop.
The syntax for a nested basic LOOP statement in PL/SQL is as follows:
LOOP
Sequence of statements1
LOOP
Sequence of statements2
END LOOP;
END LOOP;

Labeling a PL/SQL Loop


PL/SQL loops can be labeled. The label should be enclosed by double angle brackets (<< and >>) and appear at the
beginning of the LOOP statement. The label name can also appear at the end of the LOOP statement.
//program to add two numbers
CREATE PROCEDURE `add_two_numbers`(IN num1 INT, IN num2 INT)
BEGIN
DECLARE result INT;
SET result = num1 + num2
SELECT CONCAT('The sum of ', num1, ' and ', num2, ' is ', result) AS
Result;
END

2.Program to find sum of first 10 natural numbers.


3.Program to find factorial of a given number using loop.
4.Program to illustrate continue statement.
5. Program to find sum of first 100 numbers.
6. Program to generate Fibonacci series.
Named Blocks
There are several named blocks in PL/SQL. They are
 Procedure
 Function
 Package
 Cursors
 Triggers

1.Procedure
“Procedure is a subprogram is a program unit/module that performs a particular action”.
a stored procedure is a set of SQL statements that can be stored and executed on the server
syntax:
CREATE PROCEDURE procedure_name(IN parameter1 datatype, IN parameter2 datatype, OUT
output_parameter datatype)
BEGIN
-- SQL statements
-- You can use the input parameters and perform operations

-- Set the value for the output parameter


SET output_parameter = some_value;

-- More SQL statements if needed


END //
Ex:
CREATE PROCEDURE add_numbers(IN num1 INT, IN num2 INT, OUT result
INT)
BEGIN
-- Add two numbers
SET result = num1 + num2;
END;

Parameter list contains 3 parameters.


• They are IN ,OUT and INOUT. IN parameter is used to send valued to stored procedure.
OUT parameter is used to get values from stored procedure.
• procedure-body contains the executable part.
A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. A
cursor holds the rows (one or more) returned by a SQL statement. The set of rows the cursor holds is
referred to as the active set.
There are two types of cursors −
•Implicit cursors
•Explicit cursors

Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed, when
there is no explicit cursor for the statement. Programmers cannot control the implicit cursors and
the information in it.

Explicit Cursors
Explicit cursors are programmer-defined cursors for gaining more control over the context area. An
explicit cursor 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.

Working with an explicit cursor includes the following steps −


•Declaring the cursor for initializing the memory
•Opening the cursor for allocating the memory
•Fetching the cursor for retrieving the data
•Closing the cursor to release the allocated memory
Declaring the Cursor
Declaring the cursor defines the cursor with a name and the associated SELECT statement. For example −
Declare cursorname CURSOR for SELECT c1, c2, c3 FROM tablename;
Opening the Cursor
Opening the cursor allocates the memory for the cursor and makes it ready for fetching the rows returned by
the SQL statement into it. For example, we will open the above defined cursor as follows −
OPEN cursorname;
Fetching the Cursor
Fetching the cursor involves accessing one row at a time. For example, we will fetch rows from the above-
opened cursor as follows −
FETCH cursorname INTO c1, c2, c3;
Closing the Cursor
Closing the cursor means releasing the allocated memory. For example, we will close the above-opened cursor
as follows −
CLOSE cursorname;
CREATE PROCEDURE `fetch_employees4`()
BEGIN DECLARE v_ename VARCHAR(255);
DECLARE v_eno INT;
DECLARE v_finished INTEGER DEFAULT 0;
DECLARE result TEXT DEFAULT ''; -- Variable to accumulate results
DECLARE c1 CURSOR FOR SELECT ename, eno FROM emp2; -- Declare cursor
-- Declare continue handler for the end of the cursor
DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_finished = 1;
OPEN c1; -- Open the cursor read_loop: LOOP
-- Fetch data into variables
FETCH c1 INTO v_ename, v_eno;
-- Break the loop if no more rows
IF v_finished = 1 THEN
LEAVE read_loop;
END IF;
-- Your logic for processing each row
SET result := CONCAT(result, 'Employee Name: ', v_ename, ', Employee Number: ', v_eno, '\n');
END LOOP read_loop;
CLOSE c1; -- Close the cursor
-- Display the final result SELECT result AS message;
END
Functions

The PL/SQL Function is very similar to PL/SQL Procedure. The main difference between
procedure and a function is, a function must always return a value, and on the other han
a procedure may or may not return a value.
•The stored function can return only a single value defined in the function header.
•The stored function may also be called within SQL statements.
•It may not produce a result set.

The syntax of creating a stored function in MySQL is as follows:


1.CREATE FUNCTION fun_name(fun_parameter(s))
2.RETURNS datatype
3.fun_body;
CREATE FUNCTION `get_emp_name`(input_empno INT)
RETURNS varchar(100)
READS SQL DATA
BEGIN
DECLARE emp_name VARCHAR(100);
-- Select employee name into variable
SELECT ename INTO emp_name FROM emp WHERE eno = input_empno;
-- Check if employee name is found
IF emp_name IS NOT NULL
RETURN CONCAT('Welcome ', emp_name);
ELSE
RETURN 'Employee not found';
END IF;
END
What is Exception
An error occurs during the program execution is called Exception in PL/SQL.
PL/SQL facilitates programmers to catch such conditions using exception block in the program and
an appropriate action is taken against the error condition.

CREATE PROCEDURE `exception`()


BEGIN
DECLARE a INT DEFAULT 10;
DECLARE b INT DEFAULT 5;
DECLARE c INT;
DECLARE result_message VARCHAR(255); -- Variable to store the result message
-- Use a handler for SQL exceptions
DECLARE division_by_zero CONDITION FOR SQLSTATE '22012’;
DECLARE CONTINUE HANDLER FOR division_by_zero
BEGIN
SET result_message = 'Arithmetic exception: Division by zero';
END;
-- Your logic
BEGIN
SET c := a / b;
SET result_message := CONCAT('Result: ', c);
END;

-- Raise an exception for division by zero


IF b = 0 THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Arithmetic exception: Division by zero';
END IF;

-- Display the result message


SELECT result_message AS message;
END

You might also like