0% found this document useful (0 votes)
94 views

PLSQL Day 1

PL/SQL is a procedural language designed for use in Oracle Database systems. It allows users to perform tasks like: 1) Define and execute blocks of code like procedures and functions. 2) Process SQL statements and PL/SQL code as a unit. 3) Handle errors and exceptions that occur during code execution. PL/SQL code is made up of declarative statements, processing statements, and exception handling blocks that allow it to encapsulate reusable code and perform complex operations on data in the database.

Uploaded by

Carl Cj
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
94 views

PLSQL Day 1

PL/SQL is a procedural language designed for use in Oracle Database systems. It allows users to perform tasks like: 1) Define and execute blocks of code like procedures and functions. 2) Process SQL statements and PL/SQL code as a unit. 3) Handle errors and exceptions that occur during code execution. PL/SQL code is made up of declarative statements, processing statements, and exception handling blocks that allow it to encapsulate reusable code and perform complex operations on data in the database.

Uploaded by

Carl Cj
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 12

PL/SQL

******
PROCEDURAL LANGUAGE / SQL

It is a procedural language along with sql.


It is an extension to the sql.
By using PLSQL we can write programs.
Each program is used to perform at least one business task.

How to define PL/SQL?


PL/SQL is a collection of User Defined Objects like Programs,
Procedures, Functions, Triggers, Types, Packages and so on.

PL/SQL program:
***************
It is a collection of programming statements
and SQL queries.

Advantages:
***********
--> Multiple queries are executed parllelly.
--> It reduces number of hits to the database server.
--> It is increasing n/w performance.
--> Modularity ( dividing a big task into smaller modules )
--> Enhansibility ( It can easily accept the future changes )
--> Reusability (create a program once and execute it any
number of times)

PL/SQL Programs are divided into 2 categories.

They are
i) Anonymous Blocks / Programs
These objects not saved in the database.
These program's logic is included in the
User Interface application Logic.

ii) Sub Programs


These objects permanently saved in the database.
STORED PROCEDURES
FUNCTIONS

-----------------------------------------------------------------------------------
-
i) Anonymous Blocks:
********************
It is a PL/SQL program which is not saved in the DataBase Server.
It is used to call any sub program.

STRUCTURE:
**********
DECLARE [Optional]
-----
-----
BEGIN [Mandatory]
-----
-----
EXCEPTION [Optional]
-----
-----
END; [Mandatory ]
/* end of program */

/ [Enter] [ It will compile and execute the program in SQL*PLUS ]

DECLARE block:
--------------
It contains declaration statements.
In this block we can declare variables.
Variables are useful to store values.
These values are useful for complete program execution.

What is a variable?
A variable is a name with min length 1 character and max length 30 chars.
Variables are also known as place holders / literals / Identifiers.

syn:
var DATATYPE(size);

Ex: v_eno int;


v_name varchar2(20);
v_sal number(5);
v_jdate date;

--> Based on datatype and size , temporary reserved for the variable.

BEGIN block:
************
This block is also known as EXECUTION block.
We can write 3 types of statements.

They are

--> Assignment Statements


--> OutPut Statements
--> Data Processing Statements

i) Assignment stmts:
********************
These are useful to store values into the variables by using
assignment operator [ := ] or by using SELECT query with
INTO keyword.

syn-1: BY USING ASSIGNMENT OPERATOR

var := value / expression / Function_calling stmt;

Ex: v_eno := 7654;


Ex:
declare
x int;
y int;
z int;
begin
x:=100;
y:=200;
z:=x+y;

syn-2: By Using SELECT Query with INTO keyword

select col1, col2, ....,coln


INTO
var_1, var_2,....var-n
from table
where <cond>;

Note:
1) In the above syntax, Number of column names
matched with number of variables.

2) Selecting values datatypes and sizes must compatible


with variable datatypes and sizes.

Ex: select ename,sal,hiredate


INTO
V_name,v_sal,v_jdate
from emp where empno=v_eno;

ii) Out Put stmt:


*****************
It is Used to display messages and variable values.

Oracle provides a predefined output function as follows.

DBMS_OUTPUT.PUT_LINE('message' or var_name);

Ex: dbms_output.put_line(' Employee Information ');


dbms_output.put_line('--------------------------');
dbms_output.put_line(v_eno);
dbms_output.put_line(v_name);
dbms_output.put_line(v_sal);
dbms_output.put_line(v_jdate);

iii) Data Processing stmts:


***************************
Any SQL Query (select, insert, update, delete, commit, rollback)
is known as data processing stmt.

EXCEPTION Block
***************
This block is useful to handle RunTime Errors.
END;
****
Indicates end of program.

HOW TO "COMPILE" AND "EXECUTE" THE PL/SQL PROGRAM


IN sql * plus WINDOW?

/ Used to compile and execute the pl/sql program in


SQL*PLUS environment.

--> TO WRITE DEVELOPER FRIENDLY PROGRAMS, WE CAN USE


COMMENT LINES IN THE PROGRAM

--> Comment lines never compiled and never executed.

-- <Line> It is a single line comment symbol.


/* Lines */ It is a multi line comment symbol.

NOTE:

By default any program or procedure should not display output.


To display output,
The below statement ENABLE the client application,
to receive OUTPUT from server.

SET SERVEROUTPUT ON;

This is valid for current login session.

Ex:
write a program to display welcome message?

Begin
dbms_output.put_line
('welcome to oracle pl/sql');
end;

Ex:
write a program to display addition , average, max
and min of 3000 and 5000?

DECLARE
X INT;
Y INT:=5000;
vsum INT;
vavg INT;
vMAX INT;
vMIN INT;
BEGIN
X:=3000;
vsum:=X+Y;
vavg:=vsum/2;
SELECT GREATEST(X,Y) INTO vMAX FROM DUAL;
SELECT LEAST(X,Y) INTO vMIN FROM DUAL;
DBMS_OUTPUT.PUT_LINE(' SUM= ');
DBMS_OUTPUT.PUT_LINE(vsum);
DBMS_OUTPUT.PUT_LINE('AVERAGE= ');
DBMS_OUTPUT.PUT_LINE(vavg);
DBMS_OUTPUT.PUT_LINE(' MAX VALUE= ');
DBMS_OUTPUT.PUT_LINE(vMAX);
DBMS_OUTPUT.PUT_LINE(' LEAST VALUE= ');
DBMS_OUTPUT.PUT_LINE(vMIN);
END;
/

sample execution:

SUM=
8000
AVERAGE=
4000
HIGHER VALUE=
5000
MIN VALUE=
3000

PL/SQL procedure successfully completed.

NOTE:

How can i display a normal mesg after that the value of variable
immediately in the same line?

By using concatenation Operator [ || ]


**************************************
It will display the value or message after the previous
message or value.

dbms_output.put_line('mesg'||varname);

DECLARE
X INT;
Y INT:=5000;
S INT;
A NUMBER(7,2);
MX INT;
MN INT;
BEGIN
X:=3000;
S:=X+Y;
A:=S/2;
SELECT GREATEST(X,Y) INTO MX FROM DUAL;
SELECT LEAST(X,Y) INTO MN FROM DUAL;
DBMS_OUTPUT.PUT_LINE(' SUM= '||s);
--DBMS_OUTPUT.PUT_LINE(S);
DBMS_OUTPUT.PUT_LINE('AVERAGE= '||a);
--DBMS_OUTPUT.PUT_LINE(A);
DBMS_OUTPUT.PUT_LINE('HIGHER VALUE= '||mx);
--DBMS_OUTPUT.PUT_LINE(MX);
DBMS_OUTPUT.PUT_LINE('MIN VALUE='||mn);
--DBMS_OUTPUT.PUT_LINE(MN);
END;
/

sample execution:

anonymous block completed


SUM=8000
AVERAGE=4000
HIGHER VALUE=5000
MIN VALUE=3000

Types of pl/sql programs: 2

1) Static programs:
It will not accept any input values at runtime.

2) Dynamic programs:
It will accept input values at runtime.
we can make a program as dynamic as follows.
In the BEGIN Block,

var := '&var';

Enter a value for var: ----- (Hit Enter)

In the above syntax , "&" is known as substitution Operator.


It will accept a value at runtime.

STATIC PROGRAMS:

Ex:
write a program to display the employee details of
empID 7654?

declare
veno int:=7654;
vname varchar2(20);
vsal number(5);
vjob varchar2(20);
vjdate date;
vcomm number(4);
vdeptno number(3);
BEGIN
select ename,sal,job,hiredate,comm,deptno
INTO
vname,vsal,vjob,vjdate,vcomm,vdeptno
from emp
where empno=veno;
dbms_output.put_line
(chr(10)||'******* Info of 7654 ******** '||chr(10)||
'--------------------------------------------'||chr(10)||
'Name: '||vname||chr(10)||
'Salary: '||vsal||chr(10)||
'Desg: '||vjob||chr(10)||
'Join Dt: '||vjdate||chr(10)||
'Commission: '||vcomm||chr(10)||
'Working under: '||vdeptno
);
END;
/

sample output:
Info of 7654
MARTIN
1250
SALESMAN
28-SEP-81
1400
30

PL/SQL procedure successfully completed.

Ex:
declare
veno int:=7654;
vname varchar2(20);
vsal number(5);
vjob varchar2(20);
vhiredate date;
vcomm number(4);
vdeptno number(3);
BEGIN
select ename,sal,job,hiredate,comm,deptno INTO
vname,vsal,vjob,vhiredate,vcomm,vdeptno
from emp
where empno=veno;
dbms_output.put_line
(' Info of Emp id: 7654');
dbms_output.put_line
('=============================================');
dbms_output.put_line('Name of emp: '||vname);
dbms_output.put_line('Salary of emp: '||vsal);
dbms_output.put_line('Designition of emp: '||vjob);
dbms_output.put_line('Join date of emp: '||vhiredate);
dbms_output.put_line('Commission of emp: '||vcomm);
dbms_output.put_line('Deptno of emp: '||vdeptno);
dbms_output.put_line('=============================================');
END;
/

output:

Info of 7654
=============================================
Name of emp: MARTIN
Salary of emp: 1250
Designition of emp: SALESMAN
Join date of emp: 28-SEP-81
Commission of emp: 1400
Deptno of emp: 30
=============================================

PL/SQL procedure successfully completed.

Ex:
Write a program to display number of customers
from the city " Delhi " ?

DECLARE
VCITY VARCHAR2(20):='Delhi';
CUST_CNT INT;
BEGIN
SELECT COUNT(*) INTO CUST_CNT
FROM CUST_DTLS
WHERE CITY=VCITY;
DBMS_OUTPUT.PUT_LINE
(' NUMBER OF CUSTOMERS FROM '||VCITY||' = '||CUST_CNT);
END;

Ex:
Write a program to display number of male customers and number
of female customers?

declare
male_cnt int;
female_cnt int;
begin
select count(*) into male_cnt from cust_dtls where gender='M';
select count(*) into female_cnt from cust_dtls where gender='F';
dbms_output.put_line(' Number of males= '||male_cnt);
dbms_output.put_line(' Number of Females='||female_cnt);
end;

Assignments:

1) Write a program to display designition of empid 7788?

2) Write a program to display the city and mobile number of customer id " cust-5"?

3) Write a program to display the location of department " RESEARCH "?

Dynamic Progarms:
*****************
By using & (Substitution operator) operator we will make a program
as a dynamic program.

varname:='&varname';

Ex:
write a program to display details of employee for the
given empno?

declare
v_eno number(4);
v_ename varchar2(20);
v_sal number(5);
v_job varchar2(20);
v_jdate date;
V_dno int;
BEGIN
v_eno:='&v_eno';
select ename,sal,job,hiredate,deptno
INTO
v_ename,v_sal,v_job,v_jdate,v_dno
from emp
where empno=v_eno;
dbms_output.put_line
(v_eno||' Employee information ');
dbms_output.put_line
(chr(10)||'========================================================'||
chr(10)||
'EMPNAME : EMP-SALARY :EMP-DESG : EMP-JOINDATE : deptno'||chr(10)||
'============================================================'||chr(10)||
v_ename||' '||v_sal||' '||v_job||' '||v_jdate||' '||v_dno||chr(10)||
'============================================================');
end;

output:
7654 information
=====================================================
MARTIN 1250 SALESMAN 28-SEP-81
=====================================================

output:
7788 information
=====================================================
SCOTT 3000 ANALYST 19-APR-87
=====================================================

Ex:
Write a program to display the number of emps in the given deptno?

declare
vdno number(2);
empcnt int;
begin
vdno:='&vdno';
select count(empno) into empcnt
from emp
where deptno=vdno;
dbms_output.put_line
(chr(10)||' No. of emps in Department : '||vdno||': = '||empcnt);
end;

output:
number of emps in 20 = 5

Ex:
number of emps in 30 = 6

Ex:
write a program to display the dept details under
which the employee is working with given id?

declare
veno number(4);
vdno number(4);
vdname varchar2(20);
vloc varchar2(20);
begin
veno:=&veno;
select * into vdno,vdname,vloc from dept
where deptno=(select deptno from emp where empno=veno);
dbms_output.put_line
(chr(10)||' department details of employee Id: '||
chr(10)||vdno||' '||vdname||' '||vloc);
end;

Ex output:
department details of employee : 7902
20 RESEARCH DALLAS

Ex output:
department details of employee : 7788
20 RESEARCH DALLAS

Assignment:

1) write a program to display the total salary i am paying to deptno 30 employees?

2) write a program to display the "number of male customers" from the given city?

3) Write a program to display the number of emps working under given deptno?

4) write a program to find the number of emps working with given designition?

5) Write a program to find and display total salary paying to given dept name?

declare
vdname varchar2(20);
tsal number;
begin
vdname:='&vdname';
select sum(sal) into tsal
from emp
where deptno=(select deptno from dept where dname=vdname);
dbms_output.put_line(' Given dept name: '||vdname);
dbms_output.put_line(' Total Salary: '||tsal);
end;
-----------------------------------------------------------------------------------
---------------------
Ex:

declare
vsal number(4);
vcnt int;
begin
vsal:='&vsal';
select count(*) into vcnt
from emp
where sal>vsal;
dbms_output.put_line('Given salary: '||vsal);
dbms_output.put_line
(' Number of emps having more salary than given salary: '||vcnt);
end;

Ex:
write a program to display total funds under given act_type?

declare
v_act_type varchar2(10);
v_funds number(8,2);
begin
v_act_type:='&v_act_type';
select sum(act_bal) into v_funds
from cust_act_dtls
where act_type=v_act_type;
dbms_output.put_line
(' Account Type: '||v_act_type);
dbms_output.put_line
(' Total Funds: '||v_funds);
end;

Ex:
Write a program to insert a record into dept table?

declare
vdno int;
vdname varchar2(20);
vloc varchar2(10);
begin
vdno:='&vdno';
vdname:='&vdname';
vloc:='&vloc';
insert into dept values
(vdno,vdname,vloc);
dbms_output.put_line
(' New dept launched: '||vdname);
end;

--WRITE A program to register a customer by taking customer names,city and


--gender?

declare
custname varchar2(10);
city varchar2(10);
gender char;
custid number(6);
begin
custname:='&custname';
city:='&city';
gender:='&gender';
insert into cust_dtls values
(customerno.nextval,custname,city,gender);
select max(cno) into custid from cust_dtls;
dbms_output.put_line
(chr(10)||' Registered Successfully'||chr(10)||
'Hi, '||custname||' Welcome.'||' Your id is: '||custid||' for any future
reference');
end;

Ex: write a program to display customer account details for the


given customer name?

declare
vcname varchar2(20);
vactno number(12);
vacttype varchar2(10);
vopendate date;
vactbal number;
vccode varchar2(10);
begin
vcname:='&vcname';
select actno,act_type,act_open_date,act_bal,cust_code
into
vactno,vacttype,vopendate,vactbal,vccode
from cust_act_dtls
where cno =(select cno from cust_dtls where cname=vcname);

dbms_output.put_line('Account details of '||upper(vcname));


dbms_output.put_line('*************************************');
dbms_output.put_line('Account Number='||vactno);
dbms_output.put_line('Account Type='||vacttype);
dbms_output.put_line('Account Open Date='||vopendate);
dbms_output.put_line('Account Balance='||vactbal);
dbms_output.put_line('Customer Code='||vccode);
end;

Note:

Generally, we need to declare a variable with column data


type otherwise we will get compatibility issues.

To store a complete record in to a variable we need declare a


variable as TABLE BASED RECORD type variable.

-----------------------------------------------------------------------------------
---

You might also like