Anda di halaman 1dari 37

SQL (Structured Query Language)

Student
Roll no. Name Marks Grade
1 Amit 75 A
2 Raj 73 B
3 Kapil 35 D
4 Manoj 63 C
5 Piyush 65 B
6 Ravi 69 B
7 Amrita 71 B

Table …. Relation
Columns …. Attributes …. fields
Degree …. number of columns in a table / relation 4
Cardinality …. number of rows in a relation 7
Rows …. Tuples …. Records

 Data Types
1. char (size)
2. varchar2(size)
3. number
4. date

 SQL Commands

 CREATE TABLE command


Example:
CREATE TABLE employee
( ecode number (5),
ename varchar2(20),
job char(20),
salary number(9,2),
grade char(2),
doj date );

 Constraints
1. Primary key
2. Default
3. Not Null
4. Check
5. Unique
6. Foreign key

Example :
CREATE TABLE employee
( ecode number(5) Primary Key,
ename varchar2(20) unique,
sex char(1) Not Null,
grade char(2) default ‘E1’,
salary number(9,2) check(salary between 2000 and 5000));

 Applying Table Constraints

CREATE TABLE Items


(icode char(5) Not Null,
Descp char(20) Not Null,
rol number(5),
qoh number (5),
unique (icode , descp),
check (rol<qoh));

 Viewing a Table Structure


desc emp;
Or
describe emp;

 Inserting Data into Table(Insert Command)


Table Structure:
Emp (ecode, ename, job, salary, doj, grade)

Example:
Insert into Emp
values (111, ‘Raj’, ‘Manager’ , 9000, ‘1– mar– 2005’, ‘A‘);

Insert into Emp (ecode, ename, job, grade)


values( 111, ’Raj’, ’Manager’, ’A’);

Insert into Emp


Values (&Ec, ‘&En’, ‘&Jb’, &sal, ‘&dj’, ‘&grd’);

Insert into Emp


Values (111, ‘Raj’, ‘Manager’, Null, ‘1-mar-2005’, Null);

Insert into branch1


select * from branch2
where gross > 7000;

 Update Command
1. update emp
set sal = 500;

2. update emp
set sal = 700
where job = ‘manager’;

3. update emp
set sal = sal+300
where sal > 7000;

4. update emp
set sal = sal+300 , comm = comm + 200
where ecode = 111;

5. update emp
set sal = sal + 500
where grade = ‘E3’ or grade=’E4’;

6. update emp
set grade = Null
where grade = ‘E4’;

 Delete Command
Delete from Emp;

Delete from emp


where sal < 2000;

Delete from emp


where job = ‘manager’;

 Select Command
Select * from Emp;

Select ecode, ename, job from Emp;

Select ename, job, ecode from emp;

 Distinct Keyword
Select job from Emp;

Select Distinct (job) from Emp;

Select all (job) from Emp;

 Performing Simple Calculations


Select ecode, ename, job, sal * 12, (sal*12) * 0.1 from Emp;

Select ecode, ename, job, sysdate from Emp;


 Using Column Aliases
Select ename, comm commission, sal*12 ‘annual salary‘ ,
(sal*12)*0.1 tax from Emp;

 Handiling Nulls
Select ename, comm from Emp;

Select ename, nvl (comm, 0.0) from Emp;

 Putting Text in the Query Output


Select ename, ‘gets the salary’, sal, ‘Rs.’ from Emp;

 Concatenating Strings
Select ename || job, sal from Emp;

Select ename || job ‘name and job’,


sal from Emp;

 Relational Operators
= , > , < , >= , <= , < >

 Logical Operators
And, Or, Not

 The where clause


Select * from Emp
where sal > 2000;

Select ename from Emp


where job = ‘manager’;

Select ecode, ename, sal from


Emp where comm <= 500;

Select * from Emp


where sal>5000 AND job='manager';

Select ecode, ename from Emp


where job='manager' OR sal>5000;

Select ecode, ename, grade, sal from Emp


Where (NOT grade='g1');

 Conditions based on Range(Between clause)


Select * from Emp
where sal between 5000 And 8000;

Select Ename from Emp


where comm not between 500 And 800;

 Conditions based on List (IN clause)

Select * from Emp


where job IN ('manager, 'salesman', 'clerk');

Select ename, sal from Emp


where job NOT IN ('manager’, 'salesman', 'clerk');

 Conditions based on pattern matches (LIKE clause)

Wildcard Characters ( % , _ )

Select * from Emp


where ename like 'A_ _r';

Select ename from Emp


where job like 'M%r';

Select ename, sal from Emp


where job NOT LIKE 'M%r';

Examples of Patterns:
'san%'
'%idge%'
'A_ _r'
'_ _ _ _'
'_ _ _%'
'%A_ _'
'A_ _%'

 Searching for Null


Select ecode, ename, job from Emp
where deptno is NULL;

 Order by clause
Select * from Emp
order by sal;

Select ecode, ename from Emp


where sal > 2500
order by ename;

Select * from Emp


Order by ecode Desc;

Select * from Emp


Order by sal Asc, ename Desc;

 Comments
Select ename, sal, job
/*displaying the information of employees getting sal > 3000*/
from Emp
where sal > 3000; - - checking salary

 Aggregate Functions
1. sum( ) 2. avg( ) 3. max( )
4. min( ) 5. count( ) 6. count(*)

Select sum (sal) from Emp;

Select sum (sal) from Emp


where job='Manager';

Select avg(comm)from Emp;

Select max (sal) from Emp;

Select min(sal) from Emp;

Select count(comm)from Emp;

Select count(job) from emp;

Select count(distinct job) from emp;

Select count(*) from Emp;

 Group by Clause
Select job, count(*) from Emp
Group by job;

Select job, sum(sal) from Emp


Group by job;

Select deptno, count(empno) from Emp


Group by deptno;
 Having clause
Select job, sum(sal) from Emp
Group by job
having job='Manager';

Select deptno, count(empno)from Emp


Group by deptno
having deptno=10 Or deptno=20;

Select deptno, count(*) from Emp


Group by deptno
having count(*) <=3;

Select grade, avg(sal), sum(sal) from Emp


Group by grade
having grade='E4';

 Views
Create View try as
Select * from Emp
where sal >7000;

Create View xyz as


Select ecode, ename, job from Emp
where job='Manager';

Create View try (empcode, empname, designation, empgross) as


Select ecode, ename, job, sal from Emp
where sal>2000;

Create View try ( empcode, empname, designation, annualsal ) as


Select ecode, ename, job, sal*12 from Emp
where sal>2000;

Create View try as


Select * from Emp
where sal>8000
with read only;

Create View try as


Select ename, job, deptno, loc from Emp, Dept
where emp.deptno = dept.deptno;

Create or Replace view try as


Select * from Emp
where sal>3000;
 Creating Table From Existing Table
Create Table try as
( Select ecode, ename, job from Emp
where sal > 3000);

 Transactions Control Commands


1. Commit
2. Rollback
3. Savepoint

sql > insert....


sql > update ....
sql > savepoint abc;
sql >delete ....
sql >savepoint xyz;
sql > insert....
sql >rollback to savepoint abc;
sql >rollback;
sql > insert....
sql >commit;

 Alter Table Command


Alter Table Emp
Add (grade char(2));

Alter Table Emp


Add (grade char(2) Default = 'E1');

Alter Table Emp


Modify (job char(30));

 Truncating Tables
Truncate Table Emp;

 Changing Names of Objects


Rename Emp to Employee;

 Deleting Tables and Views


Drop Table Emp;

Drop View Try;

 Printing Current Date


Select sysdate from dual;
Select empno, ename, sysdate from emp;

 Creating table using select into


Select ecode, ename, job
Into try
from emp
where sal > 3000;

 Joins
Select empno, ename, job, emp.deptno, dname from emp, dept
where emp.deptno = dept.deptno;

Select empno, ename, job, emp.deptno, dname from emp,


dept where ename = ‘CLARK’ AND
emp.deptNo = dept.deptno;

Select emp.deptno, dname, empno, ename, job, sal


from emp, dept where emp.deptno = dept.deptno
order by emp.deptno, empno;

 Using table aliases


select e.deptno, dname, empno, ename, job, sal
from emp e, dept d
where e.deptno=d.deptno
order by e.deptno, empno;

select e.deptno, dname , empno ,ename , job , sal


from emp e, dept d
where e.deptno = d.deptno AND dname = ‘sales’ and sal > 1500
order by e.deptno, empno;

 Sub Queries
select empno, ename, sal from emp
where sal = (select max (sal) from emp);

select distinct job from emp


where sal > (select avg(sal) from emp);

select ename, deptno from emp where


deptno = (select deptno from emp where
ename = ‘scott’);

select itemno, itemname, price from item


where itemno in(select distinct itemno from orders);

 Deleting data based on condition from another table


delete from emp
where empno in(select empno from emp1);

delete from teacher1


where tno in (select tno from teacher where deptno = ‘d03’);

 Updating rows based on another table


Update teacher1
Set tname = ‘vishwas’
where tno = (select tno from teacher
where salary = 9100);

Update emp
Set grade = ‘A’
Where empno in (select empno from project1);

 PL-SQL

[declare] …. Optional
:
: …. all variables declarations
begin
:
: …. coding / program statements
[exception] …. Optional
:
: …. error handling statements
end;

 PL - SQL character set

Letters A-Z, a-z


Digits 0-9
Special Symbols !@#$%&*();:

 Datatypes
1. char(size)
2. varchar2(size)
3. number
4. Boolean
5. date

 Literals

Number literals
400, 37.25, NULL
Character (String literals)
'raj', 'abc', 'amit kumar', '12th', '065', 'a-45' etc.
Boolean
True, False, NULL
 Declaring Constants
Example:

Declare
x constant number:=3.73;
p constant number:=500;
m constant varchar2(10):='abc';
begin
:
:
end;
 Variables
Declare
marks number(2);
sum number(5,2):=0;
subject varchar2(30) default 'maths';
joindate date default sysdate;
dob date := ’31-mar-2004’;
perc number;
x boolean:=true;
y boolean;
z varchar2(30);
begin
marks:=75;
perc:=100;
z := ‘amit’;
dbms_output.put_line(‘my name is amit’);
dbms_output.put_line(‘the value of z is’ || z);
dbms_output.put_line(marks || sum || subject || x);
dbms_output.put_line(‘my name is’ || z);
end;

 Anchored declarations
Declare
X number(5);
Y X%type;
Z Y%type;
P X%type;
Sal Emp.salary%type;
Nm Emp.ename%type;
Begin
:
:
:
End;

 Types of variables
1. Local variables
2. Substitution variable
3. Bind / host variables (Non PL/SQL Variables)

Example:

SQL> variable x number ; /* host variable */

SQL> Declare
num number(5); /* local variables*/
x number(5);
p varchar2(30);
Begin
num: = &sal; - - substitution variable
:x := &n; - - substitution variable
p : = ‘& m’; - - substitution variable
x : = :x * 5;
End;

 Comments
1. Single line comment (- -)
2. Multi line comment (/*…………………
…………………
…………………*/)
Example:
Declare
num number(5); /* it is a
local variable */
Begin
num : = &x; - - substitution variable
end;

 Operators
+ , - , * , / , ** , || , := , = ,< > , and , != , < , > . <= , >=

25 …. 2**5 …. 32

 Saving and Executing a PL / SQL Program


1. Type the program in notepad file.
2. Save the file with .sql extension. ( Example: c:\abc.sql )
3. SQL > set serveroutput on;
4. Run the file at SQL prompt
Example:
SQL > Set Serveroutput on;
SQL > @ c:\ABC.SQL; or EXEC c:\ABC.SQL;
2 /
 PL / SQL Control Structures
1. Sequence
2. Selection
3. Iteration

 Conditional Control Statements (if statement)


Example:
Declare
marks number(5);
begin
marks := &m;
if marks >= 40 then
Dbms_output.put_line(‘Passed’);
End if;
End;
Example:
Declare
Marks number(5);
Begin
Marks := &m;
if Marks >= 40 then
dbms_output.put_line(‘Passed’);
Else
dbms_output.put_line(‘Failed’);
End if;
End;

 Multiple if Conditions
Declare
num number(5);
Begin
num := &n;
If num = 1 then
Dbms_output.put_line(‘Sunday’);
Elsif num = 2 then
Dbms_output.put_line(‘Monday’);
Elsif num = 3 then
Dbms_output.put_line(‘Tuesday’);
Elsif num = 4 then
Dbms_output.put_line(‘Wednesday’);
Elsif num = 5 then
Dbms_output.put_line(‘Thursday’);
Elsif num = 6 then
Dbms_output.put_line(‘Friday’);
Elsif num = 7 then
Dbms_output.put_line(‘Saturday’);
Else
Dbms_output.put_line(‘Invalid choice’);
End if;
End;
 Nested ifs
Declare
N number(5);
M number(5);
P number(5);
Begin
N :=10;
M :=20;
P :=30;
If n > 40 then
if m <= 30 then
Dbms_output.put_line(‘raj’);
Else
Dbms_output.put_line(‘ravi’);
End if;
Else
If P >= 93 Then
Dbms_output.put_line(‘himanshu’);
Else
Dbms_output.put_line(‘vivek’);
End if;
End if;
End;
 Loops
1. Simple loop
2. For loop
(i) Numeric For loop
(ii) Cursor For Loop
3. While loop
 Simple loop
Example:
Declare
a number(3);
Begin
a := 1;
loop
Dbms_output.put_line(‘raj’);
If a = 10 then
Exit;
End if;
a := a+1;
End loop;
End;
Example:
Declare
a number(3);
Begin
a :=1;
loop
Dbms_output.put_line(‘raj’);
Exit when a=10;
a := a+1;
End loop;
End;
Example:
Declare
a number(3);
Begin
a := 10;
Loop
Dbms_output.put_line(‘raj’);
Exit when a = 1;
a := a - 1;
End loop;
End;
 Numeric for loop
Example:
Begin
for a in 1 .. 10
loop
Dbms_output.put_line(‘raj’);
End loop;
End;
Example:
Begin
for a in reverse 1 .. 10
Loop
Dbms_output.put_line(‘raj’);
End loop;
End;
 The while loop
Example:
Declare
x number(5);
Begin
x :=1;
while x<=10
loop
Dbms_output.put_line(‘raj’);
x := x+1;
End loop;
End;
Example:
Declare
x number (5);
Begin
x := 10;
while x >= 1
loop
Dbms_output.put_line(‘raj’);
x := x - 1;
End loop;
End;
 Nested loops
Example:
Begin
for i in 1 .. 5
Loop
for j in 1 .. 3
Loop
Dbms_output.put_line(‘raj’);
End loop;
End loop;
End;
Example:
Declare
i number(3);
j number(3);
Begin
i := 1;
while i <= 5
Loop
j := 1;
while j <= 3
Loop
Dbms_output.put_line(‘raj’);
j := j+1;
End loop;
i := i+1;
End loop;
End;
 Database Interaction in PL / SQL
Only four DML SQL statements can be used in PL / SQL:-
1. Select
2. Insert
3. Update
4. Delete
Example: Display the name and salary of the employee whose code is 1175.
Declare
nm emp.ename%type;
sl emp.salary%type;
Begin
Select ename, salary into nm, sl from emp
Where ecode = 1175;
Dbms_output.put_line(nm || sl);
End;
Example: Display the name and salary of the employee whose code is given by
the user.
Declare
nm emp.ename%type;
sl emp.salary%type;
Ec emp.ecode%type;
Begin
Ec := &x;
Select ename, salary into nm, sl from emp
Where ecode = ec;
Dbms_output.put_line(nm || sl);
End;
Example: Write a PL/SQL code to insert a new record in table emp after
obtaining values from the user.
Declare
Ec number(4);
En varchar2(20);
Ej varchar2(20);
Mg number(4);
Hd date;
Sl number(7,2);
Cm number(7,2);
Dn number(3);
Begin
Ec := &x;
En := ‘&y’;
Ej := ‘&z’;
Mg := &m;
Hd :=‘&h’;
Sl := &s;
Cm := &c;
Dn := &d;
Insert into emp
Values (ec, en, ej, mg, hd, sl, cm, dn);
End;
Example: WAP to input employee code from the user & delete the record
from emp table.
Declare
Ec emp.ecode%type;
Begin
Ec := &x;
Delete from emp
Where ecode = ec;
End;
Example: Write a PL/SQL code to increase the salary of the employee by 500
if his salary is greater than 3000.
Declare
sl emp.salary%type;
Ec number(5);
Begin
Ec := &x;
Select salary into sl from emp
Where ecode = Ec;
If sl > 3000 then
Update Emp
Set salary = salary + 500
Where ecode = Ec;
End if;
End;
 Records
1. Table based records
2. Programmer defined records
3. Cursor based records
 Table Based Records
Example:
Declare
Erec emp%rowtype;
Ec emp.empno%type;
Begin
Ec := &x;
Select * into erec form Emp
Where ecode = ec;
dbms_output.put_line(Erec.empno||erec.empname||
erec.mgr||erec.hiredate||erec.sal||erec.comm||
erec.deptno);
End;
 Programmer defined records
Example:
Declare
type emprec is record
(ec emp.ecode%type,
en emp.ename%type,
ej emp.job%type,
sl emp.salary%type);

x emp.ecode%type;
erec emprec;
begin
x := &n;
select ecode, ename, job, salary into erec from emp
where ecode = x;
dbms_output.put_line (Erec.ec || erec.en || erec.ej ||
erec.sl );
End;
 Exception handling in PL / SQL
Types of exceptions
1. Predefined Exceptions
2. Undefined Exceptions
3. User Defined Exceptions
 Handling Predefined Exceptions
Example:
Declare
x number(5);
y number(5);
z number(5);
Begin
x:=&a;
y:=&b;
z:=x/y;
dbms_output.put_line(‘Result is : ’||z);
Exception:
When Zero_divide then
dbms_output.put_line(‘division by zero is not
defined’);
when others
dbms_output.put_line(‘Any other error’);
End;
Example:
Declare
nm emp.ename%type;
sl emp.salary%type;
Ec emp.ecode%type;
Begin
Ec := &x;
Select ename, salary into nm, sl from emp
Where ecode = Ec;
Dbms_output.put_line(nm || sl);
Exception:
When No_data_found then
Dbms_output.put_line(‘Employee code not
found…..’);
when too_many_rows then
Dbms_output.put_line(‘more than one row
cannot be selected…..’);
when others
dbms_output.put_line(‘Any other error’);
End;
Example:
Declare
en emp.ename%type;
ej emp.job%type;
ec varchar2(5):='ABC';
Begin
select ename, job into en, ej from emp
where ecode = ec;
dbms_output.put_line( en || ej);
Exception
when invalid_number then
dbms_output.put_line('Invalid employee id');
End;
Example:
Declare
pe_ratio number(3,1);
Begin
select price/earnings into pe_ratio
from stocks
where symbol='xyz';
insert into stats(symbol, ratio)
values('xyz', pe_ratio);
commit;
Exception
when Zero_Divide then
insert into stats (symbol, ratio)
values('xyz', NULL);
commit;
when others then
rollback;
End;
 Defining your own PL/SQL Exceptions
Example:
Declare
Invalid_sal Exception;
Invalid_comm Exception;
Ec emp.empno%type;
En emp.ename%type;
Ej emp.job%type;
Sl emp.sal%type;
Cm emp.comm % type;
Begin
Ec : = &x;
En : = ‘&y’;
Ej : = ‘&z’;
Sl : = &a;
Cm : = &b;
If sl < 1000 then
Raise invalid_sal;
End if;
If cm < 0 then
raise invalid_comm;
End if;
Insert into emp (empno, ename, job, sal, comm)
values( ec, en, ej, sl, cm);
Exception:
when invalid_sal then
DBMS_output.put_line(‘salary should be
greater than 1000’);
rollback;
when invalid_comm then
DBMS_output.put_line( ‘commission should be
greater than 0’);
rollback;
when others
rollback;
End;

 Cursors in PL/SQL
PL/SQL cursor is a mechanism that provides a way to select multiple rows of data from
the database and then processes each row individually inside a PL/SQL program.

Two types of cursors are:


Implicit Cursor: Declared for all DML and PL/SQL select statements including queries
that return only one row.
Explicit Cursor: For queries that return more than one row. Declared and named by the
programmer.

 Using Explicit Cursors


To use explicit cursor you need to perform four steps. These steps are as follows:
1. Declare the cursor
2. Open the cursor
3. Fetch rows from the cursor
4. Close the cursor

Example: Display the names, job and hire date of employees getting salary more than
3000.
Declare
Cursor try is
Select ename, job, hiredate from emp
where sal > 3000;
en emp.ename%type;
jb emp.job%type;
hd emp.hiredate%type;
Begin
open try;
loop
fetch try into en, jb, hd;
exit when try%notfound;
dbms_output.put_line( en || jb || hd );
end loop;
close try;
End;
Example: Display the information of all the managers getting salary more than 5000.
Declare
Cursor try is
Select * from Emp
where sal > 5000 AND job = 'Manager';

Erec Emp%rowtype;
Begin
Open try;
loop
fetch try into erec;
Exit when try%notfound;
dbms_output.put_line ( erec.ecode || erec.empname ||
erec.job || erec.sal || erec.grade || erec.hiredate ||
erec.mgr || erec.deptno );
End loop;
Close try;
End;
Example: Display all the information from Emp table and increase the salary of all the
managers by 500.
Declare
Cursor try is
Select * from Emp;

Erec Emp%rowtype;
Begin
Open try;
loop
fetch try into Erec;
Exit when try%notfound;
dbms_output.put_line ( erec.ecode || erec.ename ||
erec.job || erec.sal || erec.grade || erec.hiredate ||
erec.mgr || erec.deptno);
if( Erec.job = 'Manager') then
Update Emp
set sal = sal + 500
where ecode = Erec.ecode;
End if;
End loop;
Close try;
End;
 Using Parameterized Cursors
Declare
Cursor try (s number) is
Select * from Emp
where sal > s;
Erec Emp%rowtype;
n number(7,2);
Begin
n := &m;
open try( n ); Or open try (2000);
loop
fetch try into Erec;
exit when try%notfound;
dbms_output.put_line ( erec.ecode || erec.ename ||
erec.job || erec.sal || erec.grade || erec.hiredate ||
erec.mgr || erec.deptno );
End loop;
Close try;
End;
Example:
Declare
Cursor try (s number, j varchar2) is
Select * from Emp
where sal > s AND job = j;
Erec Emp%rowtype;
n number(7,2);
m varchar2(30);
Begin
n := &a;
m := ‘&b’;
open try( n, m );
Or open try (2000, m);
Or open try (n, ‘manager’);
Or open try (3000, ‘manager’);

loop
fetch try into Erec;
exit when try%notfound;
dbms_output.put_line ( erec.ecode || erec.ename ||
erec.job || erec.sal || erec.grade || erec.hiredate ||
erec.mgr || erec.deptno );
End loop;
Close try;
End;

Example:
Declare
Cursor try (s number default 2500) is
Select ename, job, hiredate from Emp
where sal > s;
en emp.ename%type;
jb emp.job%type;
hd emp.hiredate%type;
n number(7,2);
Begin
n := &m;
Open try(n); Or Open try;
loop
fetch try into en, jb, hd;
exit when try%notfound;
dbms_output.put_line( en || jb || hd );
End loop;
Close try;
End;
 Cursor Based Records
Example:
Declare
Cursor try is
Select ename, job, hiredate from Emp
where sal > 3000;
crec try%rowtype;
Begin
Open try;
loop
fetch try into crec;
exit when try%notfound;
dbms_output.put_line(crec.ename || crec.job ||
crec.hiredate );
End loop;
Close try;
End;
 Cursor for loops
Example:
Declare
Cursor try is
select ename, job, hiredate from emp
where sal > 3000;
Begin
for crec in try
loop
dbms_output.put_line ( crec.ename || crec.job ||
crec.hiredate );
End loop;
End;
 Cursor for loops with Parameters
Example:
Declare
Cursor try (s number) is
select ename, job, hiredate from emp
where sal > s;

n number (8, 2);


Begin
n := &a;
for crec in try (n)
loop
dbms_output.put_line ( crec.ename || crec.job ||
crec.hiredate );
End loop;
End;
 Advantages of using cursor for loops

1. Cursor for loop opens the cursor automatically that’s why no need of opening the
cursor.
2. Cursor for loop closes the cursor automatically i.e. why no need of closing the
cursor.
3. Cursor for loop itself defines the cursor based record.
4. Cursor for loop fetches the data into the record variable with each loop iteration.
5. Cursor for loop checks for the not found condition after each fetch.

 Procedures and Functions

 Types of blocks in PL/SQL


1. Anonymous blocks
2. Named blocks
i. Procedures
ii. Functions
iii. Triggers
iv. Packages

 Syntax (procedure):
< header > is/as
< Declarative section >
(variable declarations)

begin
Execution section (coding)

exception
Exception handling

end;

 Procedures without arguments


Example:
(Filename: c:\main.sql)

Begin
DBMS_output.put_line(‘rajeev’);
DBMS_output.put_line(‘vivek’);
Print;
DBMS_output.put_line(‘vishal’);
Print;
Print;
DBMS_output.put_line(‘ritesh’);
Print;
DBMS_output.put_line(‘harleen’);
End;

(Filename : c:\sub.sql)
Create or replace procedure print As

Begin
DBMS_output.put_line(‘rishi’);
DBMS_output.put_line(‘jai’);
DBMS_output.put_line(‘abhishek’);
End Print;

Now follow these steps


1. sql > set serveroutput on;
2. sql > @ c:\ sub.sql;
procedure created
sql > @ c:\ main.sql;
2 /
 Listing errors
sql > c:\abc.sql;
procedure created with compilation errors
sql > show errors;
…………….....................
………………………….
………………………….
………………………….
 Procedure with parameters
Example: Pl / sql code to add 2 numbers
Declare
A number(5);
B number(5);
C number(5);
Begin
A : = &x;
B : = &y;
C : = A + B;
DBMS_output.put_line(‘sum is ‘ || C);
End;

Example: PL/SQL code to add two numbers using procedures.


(Filename : c:\ main.sql)

Declare
A number(5);
B number(5);
Begin
A : = &x;
B : = &y; Actual parameters

Add(A,B);
Or
Add(5,10);
Add(a); …. Error
Add(5,a,b); …. Error
End;

(Filename : c:\sub.sql) formal parameters

Create or replace procedure add ( n number, m number) as


r number(5);
begin
r := n + m;
DBMS_output.put_line(‘sum is ‘ || r);
End add;

Example : Procedure to concatenate two strings.


(File Name: c:\main.sql)

Declare
A varchar2(20);
B varchar2(20);
Begin
A : = ‘&x’;
B : = ‘&y’;
Con(a,b);
Or
Con(‘raj’,‘kumar’); actual parameters
End;

(Filename: c:\sub.sql)

Create or replace procedure con


(n varchar2 , m varchar2) as
formal parameters
r varchar2(40);
begin
r : = n||m;
DBMS_output.put_line(‘Resultant String is ‘ || r);
End con;

Example: Write a pl/sql procedure, which accepts a employee code as parameter &
displays the name, job & salary of the employee.
(Filename: c:\main.sql)
Declare
En number(5);
Begin
En : = &x;
Dispdetails(en);
End;

(Filename: c:\sub.sql)

Create or replace procedure dispdetails(n number) as


Nm emp.ename%type;
Jb emp.job%type;
Sl emp.sal%type;
Begin
Select ename, job, sal into nm, jb, sl from emp where ecode = n;
DBMS_output.put_line(nm || jb || sl);
End dispdetails;

Example: Write a pl/sql procedure which accepts the salary as parameter & displays
ename, job, & dept number of all the employees getting salary more than the given salary.
(File name: c:\ main.sql)

Declare
Sl emp.sal%type;
Begin
Sl : = &x;
Dispdetails(sl);
End;

(Filename: c:\sub.sql)

Create or replace procedure dispdetails(s number) as


Cursor try(p number) is
select ename, job, deptno from emp where sal > p;
Crec try%rowtype;
Begin
Open try(s);
Loop
Fetch try into crec;
Exit when try%notfound;
DBMS_output.put_line(crec.ename||crec.job||crec.deptno);
End loop;
Close try;
End dispdetails;

 IN, OUT, and INOUT Parameters


Example:
(Filename : c:\main.SQL)
Declare
A number(5);
B number(5);
C number(5);
Begin
A : = &n;
B : = &m;
Add( a, b, c);
DBMS_output.put_line(‘sum is ‘ || c);
End;

(Filename: c:\sub.sql)

Create or replace procedure add


(p in number, q in number, r out number ) is
begin
r : = p + q;
end add;

Example: Inout parameters


(Filename: c:\main.sql)

declare
a number(5);
b number(5);
begin
a : = &x;
b : = &y;
add(a, b);
DBMS_output.put_line(‘sum is ‘|| b);
End;

(Filename : c:\sub.sql)

Create or replace procedure add


( p in number, q inout number ) is
begin
q := p+q;
end add;

 Assigning default values to parameters


Example:
(Filename: c:\main.sql)
Declare
A number(5);
B number(5);
Begin
A : = &x;
B : = &y;
Add(a, b);
Add(a);
Add(b);
Add;
Add(2,5,7); …. Error
End;

(Filename: c:\sub.sql)

Create or replace procedure add


(n in number default 20 , m in number := 40) is
R number(5);
Begin
R := n+m;
DBMS_output.put_line(‘sum is ’||R);
End add;

 Functions
Example: Function to add two numbers.

(Filename: c:\main.sql)
Declare
A number(5);
B number(5);
C number(5);
Begin
A := &n;
B := &m;
C := add(a, b);
DBMS_output.put_line(‘sum is ’||C);
End;

(Filename: c:\sub.sql)

Create or replace function add


( n number, m number ) return number is
r number(5);
begin
r : = n+m;
return r;
or
return n+m;
end add;

Example: Function to concatenate 2 strings.


(Filename: c:\main.sql)
declare
a varchar2(20);
b varchar2(20);
c varchar2(40);
begin
a : = ‘&x’;
b : = ‘&y’;
c : = con(a, b);
DBMS_output.put_line(‘Resultant string is ‘ || c);
End;

(Filename: C:\sub.sql)

Create or replace function con


( n varchar2 , m varchar2 ) return varchar2 is
r varchar2(40);
begin
r : = n||m;
return r;
end con;

Example: Function to check that given number is even or odd.


declare
x number(5);
y boolean;
begin
x : = &n;
y := oddeven(x);
if( y = true) then
DBMS_output.put_line(‘even number’);
Else
DBMS_output.put_line(‘odd number’);
End if;
End;

Create or replace function oddeven


(m number ) return boolean as
begin
if( mod (m, 2) = 0) then
return true;
else
return false;
end if;
end oddeven;

Example: Function to return the number of employees within the given


department
declare
dn number(5);
noe number(7);
begin
dn:=&m;
noe:=countemp(dn);
DBMS_output.put_line(‘number of employees are ‘|| noe);
End;

Create or replace function countemp


(n number) return number as
x number(5);
begin
select count(*) into x from emp where deptno = n;
return x;
end countemp;

 Notation for specifying parameters


Create or replace procedure try(acctno number, amount number)is
:
:
:
:
end try;

declare
acct number(5);
amt number(5);
begin
try(acct, amt); …. positional notation
try(amount => amt, acctno => acct); …. Named notation
try(acctno => acct, amount => amt); …. Named notation.
try(acct, amount => amt); …. Mixed notation

 Obtaining procedure names created by you


select object_type, object_name from user_objects
where object_type = ‘procedure’
or object_type = ‘function’;

select text from user_source


where name = ‘procedurename’;

 Dropping stored procedures or functions


drop procedure < procedure name >;
drop function < function name >;

 Triggers
Some points about triggers
1. Triggers are named blocks like procedures.
2. The procedure is executed explicitly when the user issues a procedure call
statement from another block whereas the trigger is executed implicitly
whenever the triggering event happens(i.e. DML statement - insert, update or
delete). Also a trigger doesn’t accept arguments.

Syntax:
Create [or replace] trigger trigger_name
Before | after insert | update | delete
[of columnname, columnname]
ON table_name
[for each row]
[when condition]
begin
<statements>
end;

Example: Display the message ‘Row Updated’ after updating the salary in emp table.
Create or Replace trigger try
after update
of salary
on emp
for each row
begin
DBMS_output.put_line(‘Row Updated’);
End;

Example: Create a trigger that inserts the old row in the archive table along with current
date, whenever a row is changed in emp table.
Create or replace trigger try
After update on emp
For each row
Begin
Insert into Archive Values ( :old.empno, :old.ename, :old.job,
:old.mgr, :old.hiredate, :old.sal, :old.comm, :old.deptno, sysdate);
End;

Example: Create a trigger that prints the change in salary every time salary of the
employee is changed.
Create or Replace trigger try
After update
Of sal
On emp
For each row
Declare
X number(5);
Begin
X := :new.sal - :old.sal;
DBMS_output.put_line(:old.sal);
DBMS_output.put_line(:new.sal);
DBMS_output.put_line(X);
End;
Example: Create a trigger for update of column sal in table emp, which ensure that sal
cannot be reduced.
Create or replace trigger upsal
Before update
Of sal
on emp
for each row
Begin
If :new.sal < :old.sal then
Raise_application_error (-20001, ‘Salary cannot be
reduced’);
End if;
End;

Example: Create a trigger for table Customer that inserts the newly inserted values in the
customer_audit table in case of an insert & inserts old existing values in customer_audit
table in case of an update. The structure of customer_audit table is:
(action_date, action. item, qty, qtytype, rate, amount)

Create or replace trigger inval


before insert or update
on customer
for each row
begin
if inserting then
insert into customer_audit
values (:new.action_date, :new.action, :new.item,
:new.qty, :new.qtytype, :new.rate, :new.amount);
else
insert into customer_audit
values (:old.action_date, :old.action, :old.item, :old.qty,
:old.qtytype, :old.rate, :old.amount);
end if;
end;

Example: An HR system has an employee table that holds a row for each employee within
the company. Each record in the table has a manager field (mgr), that holds the id for the
employee’s manager. Write a trigger so that when a manager record is deleted, the mgr
field of that manager’s employees is set to NULL.

Create or replace trigger remove_mgr


after delete on emp
For each row
Begin
If :old.job = ’manager’ then
Update emp
set mgr = null
Where mgr = :old.empno;
End if;
End;
Example: Write a trigger to stop (rollback) the transaction if the course cost entered in
course table by user exceeds 3000.
Create or replace trigger highcost
Before insert or update
on course
For each row
When (:new.coursecost > 3000)
Begin
Raise_application_error (-20001, ‘The course cost is greater than
3000’);
End highcost;

Example: Change the course cost to a default value (2000) if the course cost entered by
user exceeds 3000 in course table.

Create or replace trigger replcost


Before insert or update on course
for each row.
When (:new.coursecost > 3000)
Begin
:new.coursecost := 2000;
End replcost;

Example: Create a trigger that displays the number of employees after every delete in
emp table.
Create or replace trigger emp_count
after delete on Emp
for each row
declare
n number(5);
begin
select count(*) into n from emp;
DBMS_output.put_line(‘There are now ’||n||’ employees ’);
End;
 Viewing Errors
SQL > @ c:\abc.sql;
2 /
Warning: trigger created with compilation errors.
To view the errors:
Syntax: show errors trigger <trigger_name>
Example: show errors trigger try;

 Viewing Defined Triggers


To view the list of defined triggers, you need to use data dictionary view
namely USER_TRIGGERS having following structure.

USER_TRIGGERS (columns, trigger_name, trigger_type, table_name,


triggering_event, referencing_names, trigger_body)

Example:
Select trigger_name from user_triggers;

Example:
Select * from user_triggers
Where trigger_name = ‘try’;
 Dropping Triggers

Drop trigger <trigger_name>;


Drop trigger try;

 Enabling/Disabling Triggers

Syntax:
Alter trigger < trigger_name > { Enable | Disable}
Example:
Alter trigger try Disable;
Alter trigger try Enable;

Anda mungkin juga menyukai