You are on page 1of 12

Why PL SQL?

The PL SQL language is extension to SQL language. There are lot of limitations while
working with single SQL statement. Lot of times as per business requirements user needs
to execute the set of SQL statements. There is need to execute the procedural logic in SQL
statement. For these reasons oracle has defined the procedural language with additional
procedural features:

 User will able to define the procedural logic on client side.


 User will able to execute the set of SQL statements together
 User will able to add the Business logic using PL SQL
 User will able to add the Loops, if. Else statements in the procedure.
 Using packages user will encapsulate all the business logic in to single package.
 User will able to add complex business logic as well as business rules using PL SQL.
 PL SQL provides the mechanism for developers to add the procedural component at
server level. Means PL SQL is used to add the complex business logic, business rules
in database language.

Starting with Anonymous block in PL SQL :

Let us start with the Anonymous block in PL SQL. The PL SQL language has a block
structure. The block structure should contain set of SQL statements, Set of Exceptions,
Error handlers, functions, variable declaration etc.

Syntax of PL SQL Block:


DECLARE
variable_declarations
BEGIN
program_code
EXCEPTION
exception_handlers
END;

The above is the simple block structure of PL SQL code. Every user will start with how to
write the PL SQL block. This is universal block structure of PL SQL.In this article I will try to
give you the idea of writing simple PL SQL code using the block structure.

The block structure is converted in to 3 parts :


1. Declarative Section :
In Declarative section all the variable declaration as well as function declaration is defined.
Example:
Declare
Variable1 Number (10, 2);

2. Begin section:
In between Begin and End the actual program, code is written. The business logic needs to
be added in Begin section. The set of SQL statement has been written in begin section. User
will be able to add the looping as well as if..else structure in begin section.

Example:
Declare
Variable1 Number (10, 2);
Begin
Select 6/2 into Variable1 from dual;
Dbms_output.Put_line (‘The Division of 6/2 is’||Variable1);
End;

3. Exception Section:
After Begin, section user needs to deal with the errors and exceptions. The Oracle has given
the provision to handle exceptions. The exceptions are written in exception handling block.
There are two types of exceptions in PL SQL.One is system exceptions and other is user
defined exceptions. The exceptions block is non mandatory block.

Example :
Declare
Variable1 Number (10, 2);
Begin
Select 6/2 into Variable1 from dual;
Dbms_output.Put_line (‘The Division of 6/2 is’||Variable1);
Exception when divide_by_zero then
Dbms_output.Put_line (‘Number can not be divided by zero’);
End;

I have explained the simple PL SQL block in above example.


Things to Remember:
When you are defining PL/SQL functions, procedures, and triggers, the keyword
DECLARE is not used. When defining a function, the function specification, or function
header as it is sometimes called, begins the block. Means everything, which has not
started with Declare keyword is known as PL SQL objects.

How to Run Simple PL SQL block:

Use backslash to Run Program


Set serveroutput On

Just write the program and put backslash before running it :

declare

x integer;

begin

x := 111;

dbms_output.Put_line(x);

end;

/
Output : PL/SQL procedure successfully completed
Declaring variables in PL SQL :

 Variables are nothing but name given to the storage area which is used to
manipulate the data.
 Variables can be created and modified by multiple ways.
 Each variable has particular datatype as well as specific size, which will identify the
memory allocation.
 Declaring variable will allocate the specific storage space for the variable.

Declaring variables in PL SQL Examples:

Variable is nothing but the storage area allocated to manipulate or process the data. The
variable assignment at a time of declaration is known as variable initialization.

Syntax of Declaration of variable:

Variable_Name Datatype [Constant] (Size of variable according to syntax) [:= Value of


variable]

Variable_Name:

 The Syntax of variable contain the Variable_name, which is valid name. The PL SQL has
to follow the specific format. The variable name should start with V.

 The user should define maximum of 30 character or alphanumeric variable name.

 Valid characters include letters, numerals, dollar signs, underscore and number signs.

 There is no standard naming convention but most of the programmers use V_ while
starting with variable.

Datatype (Size of variable according to syntax):

The datatype should be any datatype of that variable. It should be Number,


float,double,integer,Boolean accordingly.The size of variable should be according to the
datatype.

Constant:
Constant keyword is used to define the constants in PL SQL.The constants are variables in
which the value does not change.
: = Symbol:
The := symbol is used to define the value to the variable.

User can display the variable using DBMS_OUTPUT.PUT_LINE function which is


used in every following examples

Example 1:
Declare the varachar2 variable:
Declare

V_New varchar2(30);

Begin

DBMS_OUTPUT.Put_Line(‘V_New is declared here’);

End;
Output :
V_New is declared here.
The above example contains the declaration of the variable named V_New but that
variable is not initialized.

Example 2:
Declare varchar2 variable with initialization:
Using assignment operator user can declare as well as initialize the value in the variable.

DECLARE

V_New VARCHAR2(11) := ‘Initialization variable’;

BEGIN

DBMS_OUTPUT.PUT_LINE(V_New);

END;
Output :
Initialization variable
In Above example the variable assignment is done through the := operator. Most of
the time users making mistake using the := Operator.User is using = operator in spite
of := operator.
Example 3 :
Declare variable using default keyword
DECLARE

V_New VARCHAR2(11) not null default ‘Default Keyword’;

BEGIN

DBMS_OUTPUT.PUT_LINE(V_New);

END;
Output :
Default keyword
The above example will initialize,declares and sets the default value as ‘Default
keyword’ to V_New variable.

Example 4: := Operator in Begin Section


Variables can also be assigned values after declaration, in the executable section. This is
typically done in one of two ways, using the assignment operator (:=) or a SELECT INTO
statement.

DECLARE

V_date DATE;

BEGIN

V_date := current_date;

DBMS_OUTPUT.PUT_LINE(‘Todays Date is: ‘ ||V_date);

END;
Output:
Todays Date is : 24/JAN/2018
Example 5 : Select into Clause
User can assign the variables using Select into Clause also. This is most useful program for
PL SQL developers. In most of PL SQL programs, the Select into clause is used.

DECLARE

V_date DATE;

BEGIN

Select sysdate into V_date from dual;

DBMS_OUTPUT.PUT_LINE(‘Todays Date using select into is: ‘ ||V_date);

END;
Output:
Todays Date using select into is: 24/JAN/2018

Example 6 : Dealing with NULL Values.

There are some cases where the variable is declared but not initialized with any
value.When user try to increment the value of that variable the result is always null.

DECLARE

V_number NUMBER := 0;

BEGIN

V_number := V_number + 1;

DBMS_OUTPUT.PUT_LINE(‘My number is: ‘ || my_number);

END;
These are some most important and useful examples of Declaring variables in PL
SQL.Each and every variables has its own scope.Just like a C programming language the
PL SQL variables are also in global and local scope.
Variable Scope :
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.

Example :

DECLARE — Global variables


number1 number := 950;
number2 number := 850;
BEGIN
dbms_output.put_line(‘Outer Variable number1: ‘ || number1);
dbms_output.put_line(‘Outer Variable number2: ‘ || number2);
DECLARE — Local variables
number1 number := 1950;
number2 number := 1850;
BEGIN
dbms_output.put_line(‘Inner Variable number1: ‘ || number1);
dbms_output.put_line(‘Inner Variable number2: ‘ || number2);
END;
END; /
Output :
Outer Variable number1: 950
Outer Variable num2: 850
Inner Variable number1: 1950
Inner Variable num2: 1850
PL/SQL procedure successfully completed.
1. What is Stored Procedure? ( 100% asked Stored Procedure Interview Questions )

Stored procedures are nothing but named blocks which contains the group of SQL statements to
achieve specific functionality.A stored procedure or in simple a proc is a named PL/SQL block
which performs one or more specific task. This is similar to a procedure in other programming
languages.Stored Procedures accepts the different input parameters and gives the result as per
requirement of user. PL/SQL is executed in the database, you can include SQL statements in your
code without having to establish a separate connection.Stored Procedure reduces the network traffic
and improves the system performance.Stored procedures are used to ensure the data integrity of
database.

2. What is difference between anonymous block and Stored Procedure?

Anonymous blocks are nothing but the PL SQL statements which are written in between begin and
end which is not stored in to Database Memory. Stored Procedures are named block which are stored
in to Database memory as database objects.

3.Where the stored procedures are stored in database?

Stored Procedure is a subroutine available to applications accessing a relational database system.


Stored Procedures (sometimes called a proc, sproc, StoPro, or SP) are actually stored in the database
data dictionary.

4.What are different types of Stored Procedures?

There are two types of Stored Procedures:


1.User Defined Procedures : This category includes the code written by developers.
2.System Stored Procedures: These are stored procedures which are already written scripts in
Oracle. User just needs to run that procedure.
3.Extended Procedure
4.CLR Stored Procedure.

5.What are different usages of Stored Procedure?

Stored Procedures are named blocks which are used to add the business logic to different
programs.Procedures are used in data validation most of the times. If there is a functional
requirement where user needs to validate the data according to the customer requirement then this
logic is been added in Stored Procedure.Complex Functionalities needs huge amount of data to be
processed.Stored Procedures are used to process huge amount of data at a same time.Following are
bullet points of usages of Stored Procedure:
1.Data Validation Purpose
2.Huge Data Processsing
3.Improve System Performance
4.Adding complex logic centralized
5.Access Control Mechanism
6.Can Procedures called inside functions? Yes or No Why?
1. Stored Procedure may contain DML statements.
2. Function can’t contain DML statements.
So executing Function inside stored procedure will never break rule 1.
But executing stored procedure inside function may break rule no 2.

7.Can We call Stored Procedure inside Stored Procedure?


Yes we can call Stored Procedure inside Stored Procedure.

8.Does the data stored in stored procedure increase access time or execution time? Explain.

Data stored in stored procedures can be retrieved much faster than the data stored in SQL database.
Data can be precompiled and stored in Stored procedures. This reduces the time gap between
query and compiling as the data has been precompiled and stored in the procedure. To avoid
repetitive nature of the data base statement caches are used.

9. Can someone able to call DDL in Stored Procedure?


Yes we can call the DDL statement in Stored Procedure. Using Execute Immediate we can call the
DDL statements in Stored Procedures.

10.What are advantages of Stored Procedure?


There are following advantages of Stored Procedures:
1.Reduce Network usage between Client and Server.
2.Improved Security
3.Fast Data Processing
4.Performance Tuning of Application
5.Reduced Development cost and increase relibility
6.Encapsulating the different complex logic
7.Security

11.What is mean by implementing the Business Logic in stored procedure?

Stored procedures implement business logic into the database. It is embedded as API and this reduces
the implementation of Logic code again explicitly. Implementation of business logic internally
reduces the chances of data becoming corrupt.

12.What are different parameters of Stored Procedures?

We can pass parameters to procedures in three ways.


1) IN-parameters
2) OUT-parameters
3) IN OUT-parameters

13.Can Procedure contain return value?


Procedure may or may not contain return value. Function must return the value.
14.How one can execute the procedure?

There are two ways to execute a procedure.


1) From the SQL prompt.
EXECUTE [or EXEC] procedure_name;
2) Within another procedure – simply use the procedure name.
procedure_name;

15.How to delete procedure?

There are two ways to delete specific procedure:


1.By using the Editor :
By using any SQL editor (toad,SQL developer) user can delete procedure by right clicking the
procedure name and choose delete option.
2.By using Command :
Using following command user can delete procedure.
Drop procedure Procedure_name;

16.Explain different modes of procedures?

There are 3 different modes of Procedure:


1.In
2.Out
3.In/Out
1.In mode

17.Explain different modes of procedures?


There are 3 different modes of Procedure:
1.In
2.Out
3.In/Out

1.In mode :
An IN parameter lets you pass a value to the subprogram. It is a read-only parameter.
Inside the subprogram, an IN parameter acts like a constant. It cannot be assigned a value.
You can pass a constant, literal, initialized variable, or expression as an IN parameter. You
can also initialize it to a default value; however, in that case, it is omitted from the
subprogram call. It is the default mode of parameter passing. Parameters are passed
by reference.

2.Out mode:
An OUT parameter returns a value to the calling program. Inside the subprogram, an OUT
parameter acts like a variable. You can change its value and reference the value after
assigning it. The actual parameter must be variable and it is passed by value.
3.In/Out mode:
An IN OUT parameter passes an initial value to a subprogram and returns an updated value
to the caller. It can be assigned a value and the value can be read.

The actual parameter corresponding to an IN OUT formal parameter must be a variable, not
a constant or an expression. Formal parameter must be assigned a value. Actual
parameter is passed by value.

18.Explain IN/OUT mode with example?


An IN OUT parameter passes an initial value to a subprogram and returns an updated value
to the caller. It can be assigned a value and the value can be read.

Following is the example of IN/OUT mode:

DECLARE
a number;
b number;
c number;
PROCEDURE findMax(x IN number, y IN number, z OUT number) IS
BEGIN
IF x > y THEN
z:= x;
ELSE
z:= y;
END IF;
END;
BEGIN
a:= 147;
b:= 457;
findMax(a, b, c);
dbms_output.put_line(' The maximum of (147, 457) : ' || c);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −

The maximum of (147, 457) : 457

PL/SQL procedure successfully completed.

You might also like