0% found this document useful (0 votes)
30 views17 pages

Basics of PL/SQL Programming Guide

The document provides an overview of PL/SQL programming, including variable declaration, output display, comments, user input, and the use of cursors. It also covers stored procedures and functions for data manipulation, as well as triggers that automatically execute in response to specific database events. Key concepts include implicit and explicit cursors, parameter modes in subprograms, and the syntax for creating triggers.

Uploaded by

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

Basics of PL/SQL Programming Guide

The document provides an overview of PL/SQL programming, including variable declaration, output display, comments, user input, and the use of cursors. It also covers stored procedures and functions for data manipulation, as well as triggers that automatically execute in response to specific database events. Key concepts include implicit and explicit cursors, parameter modes in subprograms, and the syntax for creating triggers.

Uploaded by

citygold1001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

EXNO : 07 Simple PL/SQL programs

AIM:
To study about basics of PL/SQL program and control statements in PL/SQL.

Syntax & Code:

PL/SQL identifiers

There are several PL/SQL identifiers such as variables, constants, procedures,


cursors, triggers etc.
Variables:

Like several other programming languages, variables in PL/SQL must be declared prior to its
use. They should have a valid name and data type as well.
Syntax for declaration of variables:
variable_name datatype [NOT NULL :=
value ];

Example to show how to declare variables in PL/SQL :

SQL> SET SERVEROUTPUT


ON; SQL> DECLARE var1
INTEGER; var2 REAL;
var3 varchar2(20) ;
BEGIN
null;
END;
/
Output:
PL/SQL procedure successfully completed.

Explanation:
SET SERVEROUTPUT ON: It is used to display the buffer used by the dbms_output.
var1 INTEGER : It is the declaration of variable, named var1 which is of integer type.
There are many other data types that can be used like float, int, real, smallint, long etc. It
also supports variables used in SQL as well like NUMBER(prec, scale), varchar,
varchar2
etc.

PL/SQL procedure successfully completed.: It is displayed when the code is compiled and
executed successfully.

Slash (/) after END;: The slash (/) tells the SQL*Plus to execute the block.

1. INITIALISING VARIABLES:The variables can also be initialised just like in other


programming languages. Let us see an example for the same

CODE:

SET SERVEROUTPUT ON;


DECLARE
var1 INTEGER := 2 ;
var3 varchar2(20) := 'I Love GeeksForGeeks' ;

BEGIN
null;

END;
/
Output:
PL/SQL procedure successfully completed.

Explanation:
Assignment operator (:=) : It is used to assign a value to a variable.

2. Displaying Output:
The outputs are displayed by using DBMS_OUTPUT which is a built-in package
that enables the user to display output, debugging information, and send
messages from PL/SQL blocks, subprograms, packages, and triggers.
Let us see an example to see how to display a message using PL/SQL :
CODE:
SET SERVEROUTPUT ON;
DECLARE
var varchar2(40) := 'I love GeeksForGeeks' ;
BEGIN
dbms_output.put_line(var);
END;
/

Output:
I love GeeksForGeeks

PL/SQL procedure successfully completed.

Explanation:

dbms_output.put_line : This command is used to direct the PL/SQL output to a screen.


3. Using Comments:
Like in many other programming languages, in PL/SQL also, comments can be
put within the code which has no effect in the code. There are two syntaxes to
create comments in PL/SQL :
Single Line Comment: To create a single line comment , the symbol – – is used.
Multi Line Comment: To create comments that span over several lines, the symbol /*
and */ is used.

Example to show how to create comments in PL/SQL :

CODE:

SQL> SET SERVEROUTPUT ON;


SQL> DECLARE
-- I am a comment, so i will be ignored.
var varchar2(40) := 'I love GeeksForGeeks' ;
BEGIN
dbms_output.put_line(var);
END;
/

Output:
I love GeeksForGeeks
PL/SQL procedure successfully completed.

4. Taking input from user:


Just like in other programming languages, in PL/SQL also, we can take input from the
user and store it in a variable. Let us see an example to show how to take input from
users in PL/SQL:

CODE:

SQL> SET SERVEROUTPUT ON;


SQL> DECLARE

-- taking input for variable


a anumber := &a;
-- taking input for variable b
b varchar2(30) := &b;
BEGIN
null;
END;
/
Output:
Enter value for a: 24 old 2: a number :=
&a; new 2: a number := 24; Enter value
for b: 'GeeksForGeeks' old 3: b
varchar2(30) := &b; new 3: b
varchar2(30) := 'GeeksForGeeks';

RESULT :

PL/SQL procedure successfully completed


EX NO:8 Use of implicit & explicit cursors in data handling

Aim:

To study about implicit and explicit cursors in data handling.

Description & Code:

Introduction to Cursor

A Cursor is a pointer to this context area. Oracle creates context area for processing an SQL
statement which contains all information about the statement.

PL/SQL allows the programmer to control the context area through the cursor. A cursor holds
the rows returned by the SQL statement. The set of rows the cursor holds is referred as active
set. These cursors can also be named so that they can be referred from another place of the
code.

The cursor is of two types.

● Implicit Cursor
● Explicit Cursor

Implicit Cursor
Whenever any DML operations occur in the database, an implicit cursor is created that holds
the rows affected, in that particular operation. These cursors cannot be named and, hence they
cannot be controlled or referred from another place of the code. We can refer only to the most
recent cursor through the cursor attributes.
Explicit Cursor
Programmers are allowed to create named context area to execute their DML operations to
get more control over it. The explicit cursor should be defined in the declaration section of
the PL/SQL block, and it is created for the ‘SELECT’ statement that needs to be used in the
code.
Below are steps that involved in working with explicit cursors.

● Declaring the cursor Declaring the cursor simply means to create one named context
area for the ‘SELECT’ statement that is defined in the declaration part. The name of
this context area is same as the cursor name.

● Opening CursorOpening the cursor will instruct the PL/SQL to allocate the memory
for this cursor. It will make the cursor ready to fetch the records.
● Fetching Data from the CursorIn this process, the ‘SELECT’ statement is executed
and the rows fetched is stored in the allocated memory. These are now called as active
sets. Fetching data from the cursor is a record-level activity that means we can access
the data in a record-by-record way. Each fetch statement will fetch one active set and
holds the information of that particular record. This statement is same as ‘SELECT’
statement that fetches the record and assigns to the variable in the ‘INTO’ clause, but
it will not throw any exceptions.

● Closing the CursorOnce all the record is fetched now, we need to close the cursor so
that the memory allocated to this context area will be released.

Syntax:
DECLARE
CURSOR <cursor_name> IS <SELECT statement^>
<cursor_variable declaration>
BEGIN
OPEN <cursor_name>;
FETCH <cursor_name> INTO <cursor_variable>;
.
.
CLOSE <cursor_name>;
END;

● In the above syntax, the declaration part contains the declaration of the cursor and the
cursor variable in which the fetched data will be assigned.
● The cursor is created for the ‘SELECT’ statement that is given in the cursor
declaration.
● In execution part, the declared cursor is opened, fetched and closed.

Cursor Attributes
Both Implicit cursor and the explicit cursor has certain attributes that can be accessed. These
attributes give more information about the cursor operations. Below are the different cursor
attributes and their usage.
Cursor
Description
Attribute
It returns the Boolean result ‘TRUE’ if the most recent fetch operation
%FOUND
fetched a record successfully, else it will return FALSE.
This works oppositely to %FOUND it will return ‘TRUE’ if the most
%NOTFOUND
recent fetch operation could not able to fetch any record.
It returns Boolean result ‘TRUE’ if the given cursor is already opened,
%ISOPEN
else it returns ‘FALSE’
%ROWCOUN It returns the numerical value. It gives the actual count of records that got
T affected by the DML activity.
Implicit Cursor Program:

Create the following table “student” and insert the following records:
SQL> CREATE TABLE cresstudent(RRN number(5),stud_name VARCHAR(9));

Table created.

SQL> select * from cresstudent;

no rows selected

SQL> INSERT INTO cresstudent(RRN,stud_name)

VALUES(101,'Sam'); 1 row created.

SQL> INSERT INTO cresstudent(RRN,stud_name)

VALUES(102,'Vaibav'); 1 row created.

SQL> select * from cresstudent;

RRN STUD_NAME
---------- ---------
101 Sam
102 Vaibav

SQL> DECLARE
2 total_rows number(2);
3 BEGIN
4 UPDATE cresstudent SET RRN=103 WHERE stud_name='Sam';
5 IF sql%notfound THEN
6 dbms_output.put_line('no cresstudents updated');
7 ELSIF sql%found THEN
8 total_rows := sql%rowcount;
9 dbms_output.put_line(total_rows || 'cresstudents updated');
10 END IF;
11 END;
12 /

PL/SQL procedure successfully completed.

SQL> select * from cresstudent;

RRN STUD_NAME
---------- ---------
103 Sam
102 Vaibav

EXPLICIT CURSOR
SQL> set serveroutput on;
SQL> DECLARE
2 [Link]%type;
3 cnamecresstudent.stud_name%type;
4 CURSOR c_stud is SELECT RRN,stud_name from cresstudent;
5 BEGIN
6 OPEN c_stud;
7 LOOP
8 FETCH c_stud into cid,cname;
9 EXIT WHEN c_stud%notfound;
10 dbms_output.put_line(cid || ' ' || cname);
11 END LOOP;
12 CLOSE c_stud;
13 END;
14 /

103 Sam
102 Vaibav

RESULT :

PL/SQL procedure successfully completed.


[Link]: 9 STOREDPROCEDURES&FUNCTIONSINDATAMANIPULATION

AIM:

To implement stored procedures and functions in data manipulation.

DESCRIPTION & CODE:

Introduction to PL/SQL Procedures & Functions:


● A subprogram is a program unit/module that performs a particular task. These
subprograms are combined to form larger programs. This is basically called the 'Modular
design'. A subprogram can be invoked by another subprogram or program which is called
the calling program.
A subprogram can be created −
● At the schema level
● Inside a package
● Inside a PL/SQL block
● It is created with the CREATE PROCEDURE or the CREATE FUNCTION
statement. Itis stored in the database and can be deleted with the DROP
PROCEDURE or DROP FUNCTION statement.
● PL/SQL subprograms are named PL/SQL blocks that can be invoked with a set
ofparameters. PL/SQL provides two kinds of subprograms −
● Functions − These subprograms return a single value; mainly used to compute
andreturn a value. A function is same as a procedure except that it returns a
value. ● Procedures − These subprograms do not return a value directly; mainly
used to perform an action.

Parameter Modes in PL/SQL Subprograms


The following table lists out the parameter modes in PL/SQL subprograms −
[Link] Parameter Mode & Description

1
IN
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
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
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.
Syntax for creating procedures and functions in PL/SQL:
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.
INrepresents 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
thefunction.
● function-body contains the executable part.
● The AS keyword is used instead of the IS keyword for creating a
standalonefunction.
Creating a Procedure
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
{IS | AS}
BEGIN
<procedure_body>
END procedure_name;
Where,

● procedure-name specifies the name of the procedure.


● [OR REPLACE] option allows the modification of an existing procedure.● 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.

● procedure-body contains the executable part.


● The AS keyword is used instead of the IS keyword for creating a standalone
procedure.

Program:
1. Finding maximum of two values using Procedures:
SQL> DECLARE
2 a number;
3 b number;
4 c number;
5 PROCEDURE findMax(x IN number, y IN number, z OUT number) IS
6 BEGIN
7 IF x > y THEN
8 z:= x;
9 ELSE
10 z:= y;
11 END IF;
12 END;
13 BEGIN
14 a:= 23;
15 b:= 45;
16 findMax(a, b, c);
17 dbms_output.put_line(' Maximum of (23, 45) : ' || c);
18 END;
19 /

PL/SQL procedure successfully completed.

2. Finding minimum of two values using Functions:

SQL> DECLARE
2 a number;
3 b number;
4 c number;
5 FUNCTION findMin(x IN number, y IN number)
6 RETURN number
7 IS
8 z number;
9 BEGIN
10 IF x < y THEN
11
12 z:= x;
13 ELSE
14 z:= y;
15 END IF;
16 RETURN z;
17 END;
18 BEGIN
19 a:= 23;
20 b:= 45;
21 c := findMin(a, b);
22 dbms_output.put_line(' Minimum of (23,45): ' || c);
23 END;
24 /

RESULT :

PL/SQL procedure suc/cessfully completed.


[Link]: 10 TRIGGER IN DATA MANIPULATION

AIM:

To implement Trigger concept in PL/SQL for displaying the grade of the student.

DESCRIPTION & CODE:

Introduction to Triggers:

Triggers are stored programs, which are automatically executed or fired when some events
occur. Triggers are, in fact, written to be executed in response to any of the following events

● A database manipulation (DML) statement (DELETE, INSERT, or UPDATE) ●A
database definition (DDL) statement (CREATE, ALTER, or DROP).
● A database operation (SERVERERROR, LOGON, LOGOFF,
STARTUP, or SHUTDOWN).
Triggers can be defined on the table, view, schema, or database with which the event is
associated.
Benefits of Triggers :
Triggers can be written for the following purposes −
● Generating some derived column values automatically
● Enforcing referential integrity
● Event logging and storing information on table access
● Auditing
● Synchronous replication of tables
● Imposing security authorizations
● Preventing invalid transactions

Creating Triggers :

The syntax for creating a trigger is −

CREATE [OR REPLACE ]TRIGGER trigger_name


{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;

Where,
● CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing
trigger with the trigger_name.
● {BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be
executed.
The INSTEAD OF clause is used for creating trigger on a view.
● {INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.
● [OF col_name] − This specifies the column name that will be updated.
● [ON table_name] − This specifies the name of the table associated with the trigger.
● [REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old
values for various DML statements, such as INSERT, UPDATE, and DELETE.
● [FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be
executed for each row being affected. Otherwise the trigger will execute just once
when the SQL statement is executed, which is called a table level trigger.
● WHEN (condition) − This provides a condition for rows for which the trigger would
fire. This clause is valid only for row-level triggers.

Code to implement Triggers for displaying grade for students in PL/SQL:

SQL> CREATE TABLE collegestudent(rollno number(3),name varchar(2),m1

number(3),m2 number(3),m3 number(3),total number(3),average number(3),result

varchar(10)); Table created.

SQL> CREATE OR REPLACE trigger trig_grade before insert on collegestudent


2 for each row
3 begin
4 :[Link]:=:new.m1+:new.m2+:new.m3;
5 :[Link]:=:[Link]/3;
6 if(:new.m1>=50 and :new.m2>=50 and :new.m3>=50) then
7 :[Link]:='pass';
8 else
9 :[Link]:='fail';
10 end if;
11 end;
12 /

Trigger created.
Triggering a Trigger :

Let us perform some DML operations on the STUDENT table. Here is one INSERT
statement, which will create a new record in the table −
insert into student (rollno,name,m1,m2,m3) values(101,’Mary’,70,80,95);

When a record is created in the student table, the above create trigger, trig_grade+ will be
fired and it will display the following result –
SQL> INSERT INTO collegestudent(rollno,name,m1,m2,m3)

VALUES(1,'Ya',50,50,60); 1 row created.

SQL> INSERT INTO collegestudent(rollno,name,m1,m2,m3)

VALUES(2,'mo',40,70,80); 1 row created.

SQL> INSERT INTO collegestudent(rollno,name,m1,m2,m3)

VALUES(3,'da',30,55,65); 1 row created.

SQL> INSERT INTO collegestudent(rollno,name,m1,m2,m3)

VALUES(4,'ta',35,78,69); 1 row created.

SQL> INSERT INTO collegestudent(rollno,name,m1,m2,m3)

VALUES(4,'wa',69,82,76); 1 row created.

SQL> INSERT INTO collegestudent(rollno,name,m1,m2,m3,total,average,result)


VALUES(5,'da',30,55,65,110,75,'pass

'); 1 row created.

SQL> INSERT INTO collegestudent(rollno,name,m1,m2,m3)

VALUES(105,'Ya',70,80,90); 1 row created.

SQL> select * from collegestudent;

ROLLNO NA M1 M2 M3 TOTAL AVERAGE RESULT


---------- -- ---------- ---------- ---------- ---------- ---------- ----------
1 Ya 50 50 60 160 53 pass
2 mo 40 70 80 190 63 fail
3 da 30 55 65 150 50 fail
4 ta 35 78 69 182 61 fail
4 wa 69 82 76 227 76 pass
5 da 30 55 65 150 50 fail
105 Ya 70 80 90 240 80 pass
7 rows selected.

RESULT :

PL/SQL procedure successfully completed.

You might also like