Introduction to PL SQL1
Introduction to PL SQL1
Outline
BEGIN
Executable section
PL/SQL and SQL Statements
EXCEPTION
Exception handlers(error handling code)
END;
Types of PL/SQL block
PL/SQL blocks are of mainly two types.
Anonymous blocks
Named Blocks
Anonymous blocks:
• These blocks start with the keyword 'DECLARE' or 'BEGIN'.
• Since these blocks do not have any reference name, these cannot be stored for later purpose. They shall be
created and executed in the same session.
Named blocks: (labeled block)
• Named blocks have a specific and unique name for them. They are stored as the database objects in the server.
• These blocks can be called from other blocks.
• The block structure is same as an anonymous block, but with a label which gives a name to the
block, put a label before DECLARE keyword.
• These blocks can be nested within other blocks. It can also contain nested blocks.
• Named blocks are basically of two types:
Procedure
Function
• Attributes %type, %rowtype,
%TYPE: PL/SQL can use the %type attribute to declare variables based on definition of columns
in a table.
%ROWTYPE: It provides the record type that represents a entire row of a table or view or columns
selected in the cursor.
Advantage:
1) I need not to know about variables data type.
2) If the database definition of a column in a table changes, the data type of a variable changes
accordingly.
• Variables
Variable is a named data items. Variables have a name and a data type .A variable must be declared before it is
used. Variables names must start with a letter an alphabet. We can not use reserved words as a variable name.
Variables can be used to store the results of query or to calculate values and hold them for some use later.It can
be used in expressions in SQL or Pl/SQL.
Assigning value to a variable can be done in two ways:
Using assignment operator := (colon followed by an equal sign)
Selecting or fetching table data values into variables.
Declaring Variables:
Variable_name type[size] [Not Null] [: =value]
Example:
V_salary Number(7) := 5000;
• Constants
• The declaration of a constant is similar to a variable declaration except the keyword CONSTANT is
required .It needs to be assigned a value in the declaration.
• Syntax:
Example:
DBMS_OUTPUT is a package that includes a number of procedures and functions that accumulate information
in a buffer so that it can be retrieved later. This functions can also be used to display messages.
Put_LINE puts a piece of information in the package buffer followed by an end of line marker. It can also be
used to display messages.
To display message ,the SERVEROUTPUT should be set to ON SERVEROUTPUT
Syntax:
SET SERVEROUTPUT [ON /OFF]
• Control Structures:
• Conditional Control
• Iterative Control
• Sequential Control
if <condition> then
sequence of statements;
end if;
• Write PL/SQL code that will except an account number from the user and debit amount of Rs. 2000 from a/c if the balance of a/c
remains minimum Rs.500. The process is to be fired on Account table. account (ac_Id, Name, bal)
Declare
ac_bal number(10,2);
ac_no varchar2(6);
debit_amt number(5) :=2000;
min_bal constant number(5,2):=500;
Begin
ac_no:=&ac_no;
select min_bal into ac_bal
from account
where ac_id=ac_no;
ac_bal:=ac_bal - debit_amt;
if ac_bal >= min_bal then
update accounts set bal=bal – debit_amt
where ac_id=ac_no;
end if;
End;
2. Iterative Control:
i) Simple loop
ii) For loop
iii) while loop
• i) Simple loop : In Oracle, the LOOP statement is used when you are not sure how many times you want
the loop body to execute and you want the loop body to execute at least once.
loop
sequence of statements;
end loop;
• ii) For loop
for counter in [reverse]start .. end
loop
sequence of statements;
end loop;
• iii) while loop
while <condition>
loop
<action>
• While Loop:
In Oracle, you use a WHILE LOOP when you are not sure how many times you will execute the loop body
and the loop body may not execute even once.
• Syntax: while loop
while <condition>
loop
<action>
end loop;
The condition tested each pass through the loop. If condition evaluate to TRUE, the loop body is executed .If
condition evaluates to FALSE ,the loop is terminated.
• Sequential Control:
• The GOTO statement changes the flow of control within a PL/SQL block.
The syntax for the GOTO statement in Oracle/PLSQL consists of two parts - the GOTO
statement and the Label Declaration:
Syntax:-
Declare
pi constant number(4,2) := 3.14;
radius number(5);
area number(10,2);
Begin
radius:=3;
while radius<=7
loop
area:=pi*power(radius,2);
insert into areas values(radius,area);
end loop;
End;
• Write a PL/SQL block of code for inverting a number 5639 to 9365.
Declare
selling_price number(10,2)
Begin
select sell_price into selling_price
from product_master
where product_no=‘p1’;
if selling_price<4000 then
goto add_old_price;
else
dbms_output.put_line(‘Current price’ || selling _price);
end if
<<Add_old_price>>
update product_master set sell_price=4000
where product_no= ‘p1’
insert into old_price (prduct_no, date_change, old_price)
values(‘p1’, sysdate, selling_price);
dbms_output.put_line(‘the new price of p1 is 4000’);
• Commit : To save the changes.
• Rollback : To roll back the changes. ROLLBACK in SQL is a transactional control language which is
used to undo the transactions that have not been saved in database. The command is only be used to undo
changes since the last COMMIT.
• Save point: creates points within the groups of transactions in which to ROLLBACK.
• Error Handling in PL/SQL:
• Types Of Exceptions:
1. predefined exceptions:
They are raised automatically by the system during run time.
1. No_data_found
2. Cursor_already_open
3. Dup_val_on_index
4. Storage_error
5. Program_error
6. Zero_divide
7. Invalid_cursor
8. Login_denied
9. Invalid_cursor
10. Too_many_rows
• User Defined Exception:
exception name <exception>;
Raise Statement:
raise <exception name>;
• Declare
exception name <exception>;
Begin
SQL sentence;
if condition then
raise <exception name>;
end if;
Exception
when <exception name> then
user defined actions to be carried out;
End;
• The X company wants to check qty_in_hand.if it is less than 500
the company wants to display msg.
Declare
lo_val exception;
qty item_master.qty_in_hand%type;
Begin
select qty_in_hand into qty
from item_master where itemcode=‘i100’;
if qty<500 then
raise lo_val;
end if;
Exception
when lo_val then
dbms_output.put_line=(‘Qty not enogh’);
End;
THANK YOU!!!