0% found this document useful (0 votes)
14 views45 pages

CHPT 2plsql

Uploaded by

Amruta Navale
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)
14 views45 pages

CHPT 2plsql

Uploaded by

Amruta Navale
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/ 45

Unit 2 : PL/SQL

The PL/SQL programming language was developed by Oracle


Corporation in the late 1980s as procedural extension language for
SQL and the Oracle relational database. Following are certain
notable facts about PL/SQL −

By:AMRUTA NAVALE
PL/SQL is a completely portable, high-performance transaction-processing
language.
 PL/SQL provides a built-in, interpreted and OS independent programming
environment.
 PL/SQL can also directly be called from the command-line SQL*Plus
interface.
 Direct call can also be made from external programming language calls to
database.
 PL/SQL's general syntax is based on that of ADA and Pascal programming
language.
 Apart from Oracle, PL/SQL is available in TimesTen in-memory
database and IBM DB2.

By:AMRUTA NAVALE
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.

By:AMRUTA NAVALE
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.

By:AMRUTA NAVALE
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.
In this chapter, we will discuss the Basic Syntax of PL/SQL which is a
block_x0002_structured language; this means that the PL/SQL programs are divided and
written
in logical blocks of code. Each block consists of three sub-parts −

By:AMRUTA NAVALE
Sections Description
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.
3Exception Handling This section starts with the keyword
EXCEPTION. This optional section
contains exception(s) that handle errors in
the program.
Every PL/SQL statement ends with a
semicolon (;). PL/SQL blocks can be nested
within other PL/SQL blocks using BEGIN and
END.

By:AMRUTA NAVALE
Following is the basic structure of a PL/SQL block −

DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;

By:AMRUTA NAVALE
The 'Hello World' Example
DECLARE
message varchar2(20):= 'Hello, World!';
BEGIN
dbms_output.put_line(message);
END;
/
The end; line signals the end of the PL/SQL block. To run the code from the SQL
command line, you may need to type / at the beginning of the first blank line after
the last line of the code. When the above code is executed at the SQL prompt, it
produces the following result −
Hello World

By:AMRUTA NAVALE
PL/SQL procedure successfully completed.
The PL/SQL Identifiers
PL/SQL identifiers are constants, variables, exceptions, procedures,
cursors, and
reserved words. The identifiers consist of a letter optionally
followed by more
letters, numerals, dollar signs, underscores, and number signs and
should not
exceed 30 characters.
By default, identifiers are not case-sensitive. So you can
use integer or INTEGER to represent a numeric value. You cannot
use a reserved
keyword as an identifier.
The PL/SQL Delimiters

By:AMRUTA NAVALE
A delimiter is a symbol with a special meaning. Following is the list of delimiters
in PL/SQL −
Delimiter Description
+, -, *, / Addition, subtraction/negation, multiplication, division
% Attribute indicator
' Character string delimiter
. Component selector
(,) Expression or list delimiter
: Host variable indicator
, Item separator
" Quoted identifier delimiter
= Relational operator
@ Remote access indicator
; Statement terminator
:= Assignment operator

By:AMRUTA NAVALE
=> Association operator
|| Concatenation operator
** Exponentiation operator
<<, >> Label delimiter (begin and end)
/*, */ Multi-line comment delimiter (begin and end)
-- Single-line comment indicator
.. Range operator
<, >, <=, >= Relational operators
<>, '=, ~=, ^= Different versions of NOT EQUAL

By:AMRUTA NAVALE
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 */.

By:AMRUTA NAVALE
 Steps for creating and executing PLSQL Block:

1. Write a PLSQL in Notepad


2. On SQL Command prompt type SET SERVEROUTPUT ON
3. Copy the PLSQL block and paste it on SQL prompt.
4. Compile the block by giving ‘/’ and press enter key.
5. If the block is compiled successfully the output will be displayed.
6. If the block consist some errors then you will receive a messes “PLSQL
block created with Compilation error”
7. Type Show Error command on SQL prompt, solve the error and recompile.
If the block is compiled successfully the output will be displayed.

By:AMRUTA NAVALE
DECLARE
-- variable declaration
message varchar2(20):= 'Hello, World!';
BEGIN
/*
* PL/SQL executable statement(s)
*/
dbms_output.put_line(message);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Hello World
PL/SQL procedure successfully completed.
PL/SQL Program Units
A PL/SQL unit is any one of the following −
 PL/SQL block
 Function
 Package
 Package body
 Procedure
 Trigger
 Type
 Type body Each of these units will be discussed By:AMRUTA
in the following
NAVALE
chapters.
Data Types
he PL/SQL variables, constants and parameters must have a valid data type, which specifies a storage format, constraints,
and a valid range of values. We will focus on the SCALAR and the LOB data types in this chapter. The other two data
types will be covered in other chapters.
S.No Category & Description

Scalar
1 Single values with no internal components, such as a
NUMBER, DATE, or BOOLEAN.

Large Object (LOB)

2 Pointers to large objects that are stored separately from other


data items, such as text, graphic images, video clips, and sound
waveforms.

Composite
3 Data items that have internal components that can be
accessed individually. For example, collections and records.

Reference
4
Pointers to other data items. By:AMRUTA NAVALE
PL/SQL Scalar Data Types and Subtypes
S.No Date Type & Description

Numeric
1
Numeric values on which arithmetic operations are performed.

Character
2 Alphanumeric values that represent single characters or strings
of characters.

Boolean
3
Logical values on which logical operations are performed.

Datetime
4
Dates and times.

By:AMRUTA NAVALE
PL/SQL provides subtypes of data types. For example, the data type
PLS_INTEGER
NUMBER has a subtype called INTEGER. You can use the subtypes
in your PL/SQL program to make the data types compatible with data 1 Signed integer in range -2,147,483,648 through 2,147,483,647,
types in other programs while embedding the PL/SQL code in represented in 32 bits
another program, such as a Java program. BINARY_INTEGER
PL/SQL Numeric Data Types and Subtypes 2 Signed integer in range -2,147,483,648 through 2,147,483,647,
represented in 32 bits
Following table lists out the PL/SQL pre-defined numeric data types
and their sub- types − BINARY_FLOAT
3
Single-precision IEEE 754-format floating-point number
BINARY_DOUBLE
4
Double-precision IEEE 754-format floating-point number
NUMBER(prec, scale)
5 Fixed-point or floating-point number with absolute value in range 1E-130
to (but not including) 1.0E126. A NUMBER variable can also represent 0

DEC(prec, scale)
6
ANSI specific fixed-point type with maximum precision of 38 decimal digits

DECIMAL(prec, scale)
7
IBM specific fixed-point type with maximum precision of 38 decimal digits

8 NUMERIC(pre, secale)

By:AMRUTA NAVALE
Floating type with maximum precision of 38 decimal digits

DOUBLE PRECISION
9 ANSI specific floating-point type with maximum precision of 126 binary digits (approximately
38 decimal digits)

FLOAT
10 ANSI and IBM specific floating-point type with maximum precision of 126 binary digits
(approximately 38 decimal digits)

INT
11
ANSI specific integer type with maximum precision of 38 decimal digits

INTEGER
12 ANSI and IBM specific integer type with maximum precision of 38 decimal digits

SMALLINT
13 ANSI and IBM specific integer type with maximum precision of 38 decimal digits

REAL
14 Floating-point type with maximum precision of 63 binary digits (approximately 18
decimal digits)
By:AMRUTA NAVALE
Following is a valid declaration −
DECLARE
num1 INTEGER;
num2 REAL;

num3 DOUBLE PRECISION; BEGIN


null; END;
/

When the above code is compiled and executed, it produces the following result − PL/SQL procedure

successfully completed
PL/SQL Character Data Types and Subtypes
Following is the detail of PL/SQL pre-defined character data types and their sub- types −

By:AMRUTA NAVALE
S.No Data Type & Description

CHAR
1
Fixed-length character string with maximum size of 32,767 bytes

VARCHAR2
2
Variable-length character string with maximum size of 32,767 bytes

RAW
3 Variable-length binary or byte string with maximum size of 32,767 bytes, not interpreted by PL/SQL

NCHAR
4 Fixed-length national character string with maximum size of 32,767 bytes

NVARCHAR2
5 Variable-length national character string with maximum size of 32,767 bytes

LONG
6
Variable-length character string with maximum size of 32,760 bytes

LONG RAW
7 Variable-length binary or byte string with maximum size of 32,760 bytes, not interpreted by PL/SQL
By:AMRUTA NAVALE
ROWID
8
Physical row identifier, the address of a row in an ordinary table

UROWID
9
Universal row identifier (physical, logical, or foreign row identifier)

PL/SQL Boolean Data Types


The BOOLEAN data type stores logical values that are used in logical operations. The logical values are the
Boolean values TRUE and FALSE and the value NULL.
However, SQL has no data type equivalent to BOOLEAN. Therefore, Boolean values cannot be used in −
 SQL statements
 Built-in SQL functions (such as TO_CHAR)
PL/SQL functions invoked from

SQL statements

By:AMRUTA NAVALE
PL/SQL Datetime and Interval Types
The DATE datatype is used to store fixed-length datetimes, which include the time of day in seconds since midnight. Valid
dates range from January 1, 4712 BC to December 31, 9999 AD.
The default date format is set by the Oracle initialization parameter NLS_DATE_FORMAT. For example, the default might
be 'DD-MON-YY', which includes a two-digit number for the day of the month, an abbreviation of the month name, and the
last two digits of the year. For example, 01-OCT-12.
Each DATE includes the century, year, month, day, hour, minute, and second. The following table shows the valid values for
each field − S.No Data Type & Description

CHAR
1
Fixed-length character string with maximum size of 32,767 bytes

VARCHAR2
2
Variable-length character string with maximum size of 32,767 bytes

RAW
3 Variable-length binary or byte string with maximum size of 32,767
bytes, not interpreted by PL/SQL

By:AMRUTA NAVALE
PL/SQL provides subtypes of data types. For example, the data type NUMBER has a subtype called INTEGER.
You can use the subtypes in your PL/SQL program to make the data types compatible with data types in other
programs while embedding the PL/SQL code in another program, such as a Java program.
PL/SQL Numeric Data Types and Subtypes
Following table lists out the PL/SQL pre-defined numeric data types and their sub- types −

By:AMRUTA NAVALE
PLS_INTEGER
1 Signed integer in range -2,147,483,648 through 2,147,483,647,
represented in 32 bits

BINARY_INTEGER
2 Signed integer in range -2,147,483,648 through 2,147,483,647,
represented in 32 bits

BINARY_FLOAT
3
Single-precision IEEE 754-format floating-point number

BINARY_DOUBLE
4
Double-precision IEEE 754-format floating-point number

NUMBER(prec, scale)
5 Fixed-point or floating-point number with absolute value in range 1E-130
to (but not including) 1.0E126. A NUMBER variable can also represent 0

DEC(prec, scale)
6
ANSI specific fixed-point type with maximum precision of 38 decimal digits

DECIMAL(prec, scale)
7 By:AMRUTA NAVALE
IBM specific fixed-point type with maximum precision of 38 decimal digits
Floating type with maximum precision of 38 decimal digits

DOUBLE PRECISION
9 ANSI specific floating-point type with maximum precision of 126
binary digits (approximately 38 decimal digits)

FLOAT
10 ANSI and IBM specific floating-point type with maximum precision of
126 binary digits (approximately 38 decimal digits)

INT
11
ANSI specific integer type with maximum precision of 38 decimal digits

INTEGER
12 ANSI and IBM specific integer type with maximum precision of 38
decimal digits

SMALLINT
13 ANSI and IBM specific integer type with maximum precision of 38
decimal digits

REAL
14 Floating-point type with maximum precision ofBy:AMRUTA
63 binary NAVALE
digits (approximately 18 decimal digits)
Following is a valid declaration −
DECLARE
num1 INTEGER;
num2 REAL;

num3 DOUBLE PRECISION; BEGIN


null; END;
/

When the above code is compiled and executed, it produces the following result −

PL/SQL procedure successfully completed


PL/SQL Character Data Types and Subtypes
Following is the detail of PL/SQL pre-defined character data types and their sub-
types −

By:AMRUTA NAVALE
S.No Data Type & Description

CHAR
1
Fixed-length character string with maximum size of 32,767 bytes

VARCHAR2
2
Variable-length character string with maximum size of 32,767 bytes

RAW
3 Variable-length binary or byte string with maximum size of 32,767
bytes, not interpreted by PL/SQL

By:AMRUTA NAVALE
NCHAR
4 Fixed-length national character string with maximum size of
32,767 bytes

NVARCHAR2
5 Variable-length national character string with maximum size of
32,767 bytes

LONG
6
Variable-length character string with maximum size of 32,760 bytes

LONG RAW
7 Variable-length binary or byte string with maximum size of 32,760
bytes, not interpreted by PL/SQL

ROWID
8
Physical row identifier, the address of a row in an ordinary table

UROWID
9
Universal row identifier (physical, logical, or foreign row identifier)

By:AMRUTA NAVALE
PL/SQL Boolean Data Types
The BOOLEAN data type stores logical values that are used in logical operations. The logical values are the
Boolean values TRUE and FALSE and the value NULL.
However, SQL has no data type equivalent to BOOLEAN. Therefore, Boolean values cannot be used in −
 SQL statements
 Built-in SQL functions (such as TO_CHAR)
PL/SQL functions invoked from SQL statements PL/SQL Datetime and Interval Types
The DATE datatype is used to store fixed-length datetimes, which include the time of day in seconds since midnight.
Valid dates range from January 1, 4712 BC to December 31, 9999 AD.
The default date format is set by the Oracle initialization parameter NLS_DATE_FORMAT. For example, the default
might be 'DD-MON-YY', which includes a two-digit number for the day of the month, an abbreviation of the month
name, and the last two digits of the year. For example, 01-OCT-12.
Each DATE includes the century, year, month, day, hour, minute, and second. The following table shows the valid values
for each field −

By:AMRUTA NAVALE
Field Name Valid Datetime Values Valid Interval
Values

-4712 to 9999 (excluding year 0) Any nonzero


YEAR
integer

MONTH 01 to 12 0 to 11

01 to 31 (limited by the values of


MONTH and YEAR, according to Any nonzero
DAY
the rules of the calendar for the integer
locale)

By:AMRUTA NAVALE
HOUR 00 to 23 0 to 23

MINUTE 00 to 59 0 to 59

00 to 59.9(n), where 9(n) is the 0 to 59.9(n),


precision of time fractional where 9(n) is the
seconds precision of
SECOND
interval
fractional
seconds

-12 to 14 (range accommodates


TIMEZONE_HOUR Not applicable
daylight savings time changes)

TIMEZONE_MINUTE 00 to 59 Not applicable

Found in the dynamic performance


TIMEZONE_REGION Not applicable
view V$TIMEZONE_NAMES

Found in the dynamic performance


TIMEZONE_ABBR Not applicable
view V$TIMEZONE_NAMES

By:AMRUTA NAVALE
PL/SQL Large Object (LOB) Data Types
Large Object (LOB) data types refer to large data items such as text, graphic images, video clips, and sound waveforms. LOB
data types allow efficient, random, piecewise access to this data. Following are the predefined PL/SQL LOB data types –

Data Type Description Size

Used to store large binary objects System-dependent.


BFILE in operating system files outside Cannot exceed 4
the database. gigabytes (GB).

Used to store large binary objects 8 to 128 terabytes (TB)


BLOB
in the database.

Used to store large blocks of 8 to 128 TB


CLOB
character data in the database.

Used to store large blocks of 8 to 128 TB


NCLOB
NCHAR data in the database.

By:AMRUTA NAVALE
PL/SQL User-Defined Subtypes

A subtype is a subset of another data type, which is called its base type. A subtype has the same valid operations as its base type, but only a subset of its
valid values.

PL/SQL predefines several subtypes in package STANDARD. For example, PL/SQL predefines the subtypes CHARACTER and INTEGER as follows

SUBTYPE CHARACTER IS CHAR; SUBTYPE INTEGER IS NUMBER(38,0);


You can define and use your own subtypes. The following program illustrates defining and using a user-defined subtype −

DECLARE

SUBTYPE name IS char(20); SUBTYPE message IS varchar2(100);

By:AMRUTA NAVALE
salutation name; greetings message;

BEGIN
salutation := 'Reader ';
greetings := 'Welcome to the
World of PL/SQL';
dbms_output.put_line('Hello
' || salutation || greetings);
END;

By:AMRUTA NAVALE
NULLs in PL/SQL
PL/SQL NULL values represent missing or unknown data and they are not an integer, a character, or any
other specific data type. Note that NULL is not the same as an empty data string or the null character
value '\0'. A null can be assigned but it cannot be equated with anything, including itself.
variable
A variable is nothing but a name given to a storage area that our programs can manipulate. Each
variable in PL/SQL has a specific data type, which determines the size and the layout of the variable's
memory; the range of values that can be stored within that memory and the set of operations that can be
applied to the variable.
The name of a PL/SQL variable consists of a letter optionally followed by more letters,
numerals, dollar signs, underscores, and number signs and should not exceed 30
characters. By default, variable names are not case-sensitive. You cannot use a reserved
PL/SQL keyword as a variable name.
PL/SQL programming language allows to define various types of variables, such as date
time data types, records, collections, etc. which we will cover in subsequent chapters. For
this chapter, let us study only basic variable types.

By:AMRUTA NAVALE
Variable Declaration in PL/SQL
PL/SQL variables must be declared in the declaration section or in a package as a global
variable. When you declare a variable, PL/SQL allocates memory for the variable's value
and the storage location is identified by the variable name.
The syntax for declaring a variable is −
variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT
initial_value]
Where, variable_name is a valid identifier in PL/SQL, datatype must be a valid PL/SQL
data type or any user defined data type which we already have discussed in the last chapter.
Some valid variable declarations along with their definition are shown below −
sales number(10, 2);

pi CONSTANT double precision := 3.1415; name

varchar2(25);
address varchar2(100);
name varchar2(25);
address varchar2(100);
By:AMRUTA NAVALE
Initializing Variables in PL/SQL
Whenever you declare a variable, PL/SQL assigns it a default value of NULL. If you want to
initialize a variable with a value other than the NULL value, you can do so during the
declaration, using either of the following −
 The DEFAULT keyword
The assignment operator For example −
counter binary_integer := 0;
greetings varchar2(20) DEFAULT 'Have a Good Day';
You can also specify that a variable should not have a NULL value using the NOT NULL
constraint. If you use the NOT NULL constraint, you must explicitly assign an initial value for
that variable.
It is a good programming practice to initialize variables properly otherwise, sometimes programs
would produce unexpected results. Try the following example which makes use of various types
of variables −

By:AMRUTA NAVALE
SQL> connect system/tiger
Connected.
SQL> SET SERVEROUTPUT ON
SQL> DECLARE
2 a integer := 10;
3 b integer := 20;
4 c integer;
5 f real;
6 BEGIN
7
8 c := a + b;
9 dbms_output.put_line('Value of c: ' || c);
10 f := 70.0/3.0;
11 dbms_output.put_line('Value of f: ' || f);
12 END;
13 /
OUTPUT:
Value of c: 30
Value of f: 23.33333333333333333333333333333333333333

PL/SQL procedure successfully completed.


By:AMRUTA NAVALE
Variable Scope in PL/SQL
PL/SQL allows the nesting of blocks, i.e., each program block may contain another inner block. If a variable is
declared within an inner block, it is not accessible to the outer block. However, if a variable is declared and
accessible to an outer block, it is also accessible to all nested inner blocks. There are two types of variable scope

 Local variables − Variables declared in an inner block and not accessible to outer blocks.
 Global variables − Variables declared in the outermost block or a package.
Following example shows the usage of Local and Global variables in its simple form −

By:AMRUTA NAVALE
Creating a Function
A standalone function is created using the CREATE FUNCTION statement.
The simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as follows −
CREATE [OR REPLACE] FUNCTION function_name [(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype {IS | AS}
BEGIN
< function_body >
END [function_name]
Where,
• function-name specifies the name of the function.
[OR REPLACE] option allows the modification of an existing function.
• The optional parameter list contains name, mode and types of the parameters.
IN represents the value that will be passed from outside and OUT represents the parameter that will be used to return a
value outside of the procedure.
• The function must contain a return statement.
• The RETURN clause specifies the data type you are going to return from the function.
• function-body contains the executable part.
• The AS keyword is used instead of the IS keyword for creating a standalone function.

By:AMRUTA NAVALE
• Example The following example illustrates how to create and call a standalone function.
• This function returns the total number of CUSTOMERS in the customers table. We will use the CUSTOMERS table
• SQL> CREATE TABLE CUSTOMERS(
• ID INT NOT NULL,
• NAME VARCHAR (20) NOT NULL,
• AGE INT NOT NULL,
• ADDRESS CHAR (25),
• SALARY DECIMAL (18, 2),
• PRIMARY KEY (ID)
• );

• Table created.

• SQL> INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


• 2 VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );

• 1 row created.

• SQL>
• SQL> INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
• 2 VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 );

By:AMRUTA NAVALE
• 1 row created.
• SQL>
• SQL> INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
• 2 VALUES (3, 'kaushik', 23, 'Kota', 2000.00 );

• 1 row created.

• SQL>
• SQL> INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
• 2 VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 );

• 1 row created.

• SQL>
• SQL> INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
• 2 VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 );

• 1 row created.

• SQL>
• SQL> INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
• 2 VALUES (6, 'Komal', 22, 'MP', 4500.00 );

• 1 row created.
By:AMRUTA NAVALE
• Select * from customers;
• +----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
• +----+----------+-----+-----------+----------+
• | 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
• | 2 | Khilan | 25 | Delhi | 1500.00 |
• | 3 | kaushik | 23 | Kota | 2000.00 |
• | 4 | Chaitali | 25 | Mumbai | 6500.00 |
• | 5 | Hardik | 27 | Bhopal | 8500.00 |
• | 6 | Komal | 22 | MP | 4500.00 |
• +----+----------+-----+-----------+----------+

• CREATE OR REPLACE FUNCTION totalCustomers


RETURN number IS
total number(2) := 0;
BEGIN
SELECT count(*) into total FROM customers;
RETURN total;
END;
/

By:AMRUTA NAVALE
While creating a function, you give a definition of what the function has to do. To use a function, you will have to call that
function to perform the defined task.
When a program calls a function, the program control is transferred to the called function. A called function performs the
defined task and when its return statement is executed or when the last end statement is reached, it returns the program
control back to the main program.
To call a function, you simply need to pass the required parameters along with the function name and if the function
returns a value, then you can store the returned value.

Following program calls the function totalCustomers from an anonymous block −

DECLARE c number(2);
BEGIN c := totalCustomers();
dbms_output.put_line('Total no. of Customers: ' || c);
END; /
When the above code is executed at the SQL prompt, it produces the following result −
Total no. of Customers: 6
PL/SQL procedure successfully completed.

By:AMRUTA NAVALE
The following example demonstrates Declaring, Defining, and Invoking a Simple PL/SQL Function that computes and
returns the maximum of two values.
DECLARE
a number;
b number;
c number;
FUNCTION findMax(x IN number, y IN number)
RETURN number IS z number;
BEGIN
IF x > y THEN z:= x;
ELSE Z:= y;
END IF;
RETURN z;
END;
BEGIN
a:= 23;
b:= 45;
c := findMax(a, b);
dbms_output.put_line(' Maximum of (23,45): ' || c);
END;
/
When the above code is executed at the SQL prompt, it produces the following result − Maximum of (23,45): 45
PL/SQL procedure successfully completed. By:AMRUTA NAVALE

You might also like