0% found this document useful (0 votes)
3 views46 pages

UNIT – 1 Procedural SQL

The document provides an overview of PL/SQL, a block-structured language used in Oracle databases, detailing its structure, including declaration, execution, exception handling, and termination sections. It covers various PL/SQL concepts such as constants, literals, control statements (like CASE and loops), and records, along with examples for better understanding. Additionally, it explains different types of loops and their syntax, emphasizing the use of records for organizing data in a structured manner.

Uploaded by

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

UNIT – 1 Procedural SQL

The document provides an overview of PL/SQL, a block-structured language used in Oracle databases, detailing its structure, including declaration, execution, exception handling, and termination sections. It covers various PL/SQL concepts such as constants, literals, control statements (like CASE and loops), and records, along with examples for better understanding. Additionally, it explains different types of loops and their syntax, emphasizing the use of records for organizing data in a structured manner.

Uploaded by

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

UNIT – 1 Procedural

SQL
PL/SQL Block Structure
• PL/SQL is a block structured language that can have multiple blocks in it.
• In PL/SQL all topics of PL/SQL language such as conditional statements, loops,
arrays, string, exceptions, collections, records, triggers, functions, procedures,
cursors etc.
• SQL stands for Structured Query Language i.e. used to perform operations on the
records stored in database such as inserting records, updating records, deleting
records, creating, modifying and dropping tables, views etc.
What is PL/SQL ?
• PL/SQL is a block structured language. The programs of PL/SQL are logical blocks
that can contain any number of nested sub-blocks. Pl/SQL stands for "Procedural
Language extension of SQL" that is used in Oracle. PL/SQL is integrated with
Oracle database (since version 7). The functionalities of PL/SQL usually extended
after each release of Oracle database. Although PL/SQL is closely integrated with
SQL language, yet it adds some programming constraints that are not available in
SQL.
• The Declaration section: Code block start with a declaration section, in which
memory variables, constants, cursors and other oracle objects can be declared
and if required initialized.

• The Begin section: Consist of set of SQL and PL/SQL statements, which describe
processes that have to be applied to table data. Actual data manipulation,
retrieval, looping and branching constructs are specified in this section.

• The Exception section: This section deals with handling errors that arise during
execution data manipulation statements, which make up PL/SQL code block.
Errors can arise due to syntax, logic and/or validation rule.

• The End section: This marks the end of a PL/SQL block.


DECLARE
-- declare variable a, b and c
-- and these three variables datatype are integer
a number;
b number;
c number;
BEGIN
a:= 10;
b:= 100;
--find largest number
--take it in c variable
IF a > b THEN
c:= a;
ELSE
c:= b;
END IF;
dbms_output.put_line(' Maximum number in 10 and 100: ' ||
c);
END;
/
DECLARE -- Local variables
-- Global variables num1 number := 195;
num1 number := 95;
num2 number := 185;
num2 number := 85;
BEGIN
BEGIN
dbms_output.put_line('Inner Variable
dbms_output.put_line('Outer Variable num1:
num1: ' || num1);
' || num1);
dbms_output.put_line('Outer Variable num2:
dbms_output.put_line('Inner Variable
' || num2); num2: ' || num2);
DECLARE END;
END;
/
PL/SQL Constants
• A constant is a value used in a PL/SQL block that remains unchanged throughout
the program. It is a user-defined literal value. It can be declared and used instead
of actual values.
• Let's take an example to explain it well:
• Suppose, you have to write a program which will increase the salary of the
employees up to 30%, you can declare a constant and use it throughout the
program. Next time if you want to increase the salary again you can change the
value of constant than the actual value throughout the program.
PL/SQL Constants cont ….
• Syntax to declare a constant:
constant_name CONSTANT datatype := VALUE;
• Constant_name:
it is the name of constant just like variable name. The constant
word is a reserved word and its value does not change.
• VALUE:
it is a value which is assigned to a constant when it is declared. It
can not be assigned later.
DECLARE BEGIN
-- constant declaration -- processing
pi constant number := 3.141592654; radius := 9.5;
-- other declarations dia := radius * 2;
circumference := 2.0 * pi * radius;
radius number(5,2);
area := pi * radius * radius;
dia number(5,2);
-- output
circumference number(7, 2);
dbms_output.put_line('Radius: ' || radius);
area number (10, 2);
dbms_output.put_line('Diameter: ' || dia);
dbms_output.put_line('Circumference: ' || cir
cumference);
dbms_output.put_line('Area: ' || area);
END;
Out put:
• After the execution of the above code at SQL prompt, it will produce
the following result:.

Radius: 9.5
Diameter: 19
Circumference: 59.69
Area: 283.53

Pl/SQL procedure successfully completed.


PL/SQL Literals
• Literals are the explicit numeric, character, string or Boolean values
which are not represented by an identifier. For example: TRUE, NULL,
etc. are all literals of type Boolean. PL/SQL literals are case-sensitive.
There are following kinds of literals in PL/SQL:
• Numeric Literals
• Character Literals
• String Literals
• BOOLEAN Literals
• Date and Time Literals
Example of these different types of
Literals:

Literals Examples

Numeric 75125, 3568, 33.3333333 etc.

Character 'A' '%' '9' ' ' 'z' '('

String Hello JavaTpoint!

Boolean TRUE, FALSE, NULL etc.

Date and Time '26-11-2002' , '2012-10-29


12:01:01'
PL/SQL Case Statement
• The PL/SQL CASE statement facilitates you to execute a sequence of statements
based on a selector. A selector can be anything such as variable, function or an
expression that the CASE statement checks to a Boolean value.
• The CASE statement works like the IF statement, only using the keyword WHEN. A
CASE statement is evaluated from top to bottom. If it get the condition TRUE,
then the corresponding THEN calause is executed and the execution goes to the
END CASE clause.
Syntax for the CASE Statement:

CASE [ expression ]
WHEN condition_1 THEN result_1
WHEN condition_2 THEN result_2
...
WHEN condition_n THEN result_n
ELSE result
END
Example of PL/SQL case statement
DECLARE
grade char(1) := 'A';
BEGIN
CASE grade
when 'A' then dbms_output.put_line('Excellent');
when 'B' then dbms_output.put_line('Very good');
when 'C' then dbms_output.put_line('Good');
when 'D' then dbms_output.put_line('Average');
when 'F' then dbms_output.put_line('Passed with Grace');
else dbms_output.put_line('Failed');
END CASE; Excellent
PL/SQL procedure successfully completed.
END;
PL/SQL Loop
• The PL/SQL loops are used to repeat the execution of one or more
statements for specified number of times. These are also known as
iterative control statements.

Syntax for a basic loop:


• LOOP
Sequence of statements;
END LOOP;
Types of PL/SQL Loops
• There are 4 types of PL/SQL Loops.
• Basic Loop / Exit Loop
• While Loop
• For Loop
• Cursor For Loop
PL/SQL Exit Loop (Basic Loop)
• PL/SQL exit loop is used when a set of statements is to be executed at least once
before the termination of the loop. There must be an EXIT condition specified in
the loop, otherwise the loop will get into an infinite number of iterations. After
the occurrence of EXIT condition, the process exits the loop.
• Syntax of basic loop:
LOOP
Sequence of statements;
END LOOP;
• Syntax of exit loop:
LOOP
statements;
EXIT;
{or EXIT WHEN condition;}
END LOOP;
• Example of PL/SQL EXIT Loop
DECLARE
Out put :
i NUMBER := 1;
BEGIN 1 to 10;
LOOP
EXIT WHEN i>10;
DBMS_OUTPUT.PUT_LINE(i);
i := i+1;
END LOOP;
END;
/
Note:-

• You must follow these steps while using PL/SQL Exit Loop.
• Initialize a variable before the loop body
• Increment the variable in the loop.
• You should use EXIT WHEN statement to exit from the Loop.
Otherwise the EXIT statement without WHEN condition, the
statements in the Loop is executed only once.
Example 2
DECLARE LOOP
VAR1 NUMBER; DBMS_OUTPUT.PUT_LINE
VAR2 NUMBER; (VAR1*VAR2);
BEGIN IF (VAR2=10) THEN
VAR1:=100; EXIT;
VAR2:=1; END IF;
VAR2:=VAR2+1;
END LOOP;
END;
PL/SQL While Loop
• PL/SQL while loop is used when a set of statements has to be
executed as long as a condition is true, the While loop is used. The
condition is decided at the beginning of each iteration and continues
until the condition becomes false.
• Syntax of while loop:
WHILE <condition>
LOOP statements;
END LOOP;
Example of PL/SQL While Loop
• DECLARE
• i INTEGER := 1;
• BEGIN
• WHILE i <= 10 LOOP
• DBMS_OUTPUT.PUT_LINE(i);
• i := i+1;
• END LOOP;
• END;
Example 2
DECLARE WHILE (VAR2<=10)
VAR1 NUMBER; LOOP
VAR2 NUMBER; DBMS_OUTPUT.PUT_LINE
BEGIN (VAR1*VAR2);
VAR1:=200; VAR2:=VAR2+1;
VAR2:=1; END LOOP;
END;
PL/SQL FOR Loop
• PL/SQL for loop is used when when you want to execute a set of statements for a
predetermined number of times. The loop is iterated between the start and end
integer values. The counter is always incremented by 1 and once the counter
reaches the value of end integer, the loop ends.
• Syntax of for loop:
FOR counter IN initial_value .. final_value LOOP
LOOP statements;
END LOOP;
PL/SQL For Loop Example 1
BEGIN
FOR k IN 1..10 LOOP
-- note that k was not declared
DBMS_OUTPUT.PUT_LINE(k);
END LOOP;
END;
Note:
• You must follow these steps while using PL/SQL FOR Loop.
• You don't need to declare the counter variable explicitly because it is
declared implicitly in the declaration section.
• The counter variable is incremented by 1 and does not need to be
incremented explicitly.
• You can use EXIT WHEN statements and EXIT statements in FOR Loops
but it is not done often.
PL/SQL For Loop Example 2
DECLARE
VAR1 NUMBER;
BEGIN
VAR1:=10;
FOR VAR2 IN 1..10
LOOP
DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);
END LOOP;
END;
PL/SQL For Loop REVERSE Example
3
DECLARE
VAR1 NUMBER;
BEGIN
VAR1:=10;
FOR VAR2 IN REVERSE 1..10
LOOP
DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);
END LOOP;
END;
PL/SQL Continue Statement
• The continue statement is used to exit the loop from the reminder if its body
either conditionally or unconditionally and forces the next iteration of the loop to
take place, skipping any codes in between.
• The continue statement is not a keyword in Oracle 10g. It is a new feature
encorporated in oracle 11g.
• For example: If a continue statement exits a cursor FOR LOOP prematurely then it
exits an inner loop and transfer control to the next iteration of an outer loop, the
cursor closes (in this context, CONTINUE works like GOTO).
Example of PL/SQL continue
statement
DECLARE DBMS_OUTPUT.PUT_LINE
x NUMBER := 0;
('Inside loop, after CONTINUE: x = ' ||
BEGIN
TO_CHAR(x));
LOOP -- After CONTINUE statement, control resum
es here EXIT WHEN x = 5;
DBMS_OUTPUT.PUT_LINE ('Inside loop: x = ' || T END LOOP;
O_CHAR(x));
DBMS_OUTPUT.PUT_LINE (' After loop: x
x := x + 1;
= ' || TO_CHAR(x));
IF x < 3 THEN
CONTINUE; END;
END IF; /
Out put:
• Inside loop: x = 0
• Inside loop: x = 1
• Inside loop: x = 2
• Inside loop, after CONTINUE: x = 3
• Inside loop: x = 3
• Inside loop, after CONTINUE: x = 4
• Inside loop: x = 4
• Inside loop, after CONTINUE: x = 5
• After loop: x = 5
PL/SQL - Records
• In this chapter, we will discuss Records in PL/SQL. A record is a data
structure that can hold data items of different kinds. Records consist
of different fields, similar to a row of a database table.
• For example, you want to keep track of your books in a library. You
might want to track the following attributes about each book, such as
Title, Author, Subject, Book ID. A record containing a field for each of
these items allows treating a BOOK as a logical unit and allows you to
organize and represent its information in a better way.
PL/SQL can handle the following
types of records
• Table-based
• Cursor-based records
• User-defined records

• Table-Based Records
• The %ROWTYPE attribute enables a programmer to create table-
based and cursorbased records.
• The following example illustrates the concept of table-based records. We
will be using the CUSTOMERS table we had created and used in the
previous chapters
• DECLARE
• customer_rec customers%rowtype;
• BEGIN
• SELECT * into customer_rec
• FROM customers
• WHERE id = 5;
• dbms_output.put_line('Customer ID: ' || customer_rec.id);
• dbms_output.put_line('Customer Name: ' || customer_rec.name);
• dbms_output.put_line('Customer Address: ' || customer_rec.address);
• dbms_output.put_line('Customer Salary: ' || customer_rec.salary);
• END;
• /
Out put:-
• Out put :-
• Customer ID: 5
• Customer Name: Hardik
• Customer Address: Bhopal
• Customer Salary: 9000

• PL/SQL procedure successfully completed


Cursor-Based Records
• The following example illustrates the concept of cursor-based records. We will be
using the CUSTOMERS table we had created and used in the previous chapters
DECLARE
CURSOR customer_cur is
SELECT id, name, address
FROM customers;
customer_rec customer_cur%rowtype;
BEGIN
OPEN customer_cur;
LOOP
FETCH customer_cur into customer_rec;
EXIT WHEN customer_cur%notfound;
DBMS_OUTPUT.put_line(customer_rec.id || ' ' || customer_rec.name);
END LOOP;
END;
Out put :-
• 1 Ramesh
• 2 Khilan
• 3 kaushik
• 4 Chaitali
• 5 Hardik
• 6 Komal

• PL/SQL procedure successfully completed.


User-Defined Records
• PL/SQL provides a user-defined record type that allows you to define the different
record structures. These records consist of different fields. Suppose you want to
keep track of your books in a library. You might want to track the following
attributes about each book

• Title
• Author
• Subject
• Book ID
Define a record type :-
• TYPE
• type_name IS RECORD
• ( field_name1 datatype1 [NOT NULL] [:= DEFAULT EXPRESSION],
• field_name2 datatype2 [NOT NULL] [:= DEFAULT EXPRESSION],
• ...
• field_nameN datatypeN [NOT NULL] [:= DEFAULT EXPRESSION);
• record-name type_name;
The Book record is declared in the
following way
DECLARE
TYPE books IS RECORD
(title varchar(50),
author varchar(50),
subject varchar(100),
book_id number);
book1 books;
book2 books;
Accessing Fields
• To access any field of a record, we use the dot (.) operator. The member access operator is coded
as a period between the record variable name and the field that we wish to access. Following is
an example to explain the usage of record −
• Program:
DECLARE
type books is record
(title varchar(50),
author varchar(50),
subject varchar(100),
book_id number);
book1 books;
book2 books;
BEGIN
-- Book 1 specification
book1.title := 'C Programming';
book1.author := 'Nuha Ali';
book1.subject := 'C Programming Tutorial';
book1.book_id := 6495407;
-- Book 2 specification
book2.title := 'Telecom Billing';
book2.author := 'Zara Ali';
book2.subject := 'Telecom Billing Tutorial';
book2.book_id := 6495700;
-- Print book 1 record
dbms_output.put_line('Book 1 title : '|| book1.title);
dbms_output.put_line('Book 1 author : '|| book1.author);
dbms_output.put_line('Book 1 subject : '|| book1.subject);
dbms_output.put_line('Book 1 book_id : ' || book1.book_id);

-- Print book 2 record


dbms_output.put_line('Book 2 title : '|| book2.title);
dbms_output.put_line('Book 2 author : '|| book2.author);
dbms_output.put_line('Book 2 subject : '|| book2.subject);
dbms_output.put_line('Book 2 book_id : '|| book2.book_id);
END;
/
Out put :-
Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700

PL/SQL procedure successfully completed

You might also like