SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
DML COMMANDS
=============================================================
The Commands that are listed under Data Manipulation Language(DML) are,
INSERT Command,
SELECT Command,
UPDATE Command,
DELETE Command.
=============================================================
PPPA
A
G
E
O
AG
GE
E 111 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
INSERT Command:
INSERT Command is used to Insert Values to a Table.
-------------------------------------------------------------------------------------------------------
Syntax:INSERT INTO Table_Name( Column_Name,
Column_Name, . . . . .)
VALUES( Value, Value, . . . . . );
Examples:SQL> insert into client_master values('C00001','Ivan Bayross',
2
'No 15, Vasanth Vihar','Mumbai','Maharashtra',
3
400054,15000.00);
1 row created.
SQL> insert into client_master values('C00002','Basu Navidngi',
2
'27,Heritage Apartments','Mumbai','Maharashtra',
3
400056,10000.00);
1 row created.
SQL> insert into client_master values('C00003', 'Ravi Sreedharan',
2
'18, Luxury Street', 'Delhi', 'New Delhi',
3
100001,2000.00);
1 row created.
SELECT Command:
SELECT Command is used for the following,
Select All Rows in a Table,
Select Particular Rows of a Table,
Select Rows that Satisfies a Condition.
------------------------------------------------------------------------------------------------------PPPA
A
G
E
O
AG
GE
E 222 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
Syntax:-
Selecting All Rows in a Table:SELECT * FROM Table_Name;
Select Particular Rows of a Table:SELECT Column_Name, Column_Name FROM
Table_Name;
Select Rows that Satisfies a Condition:SELECT * FROM Table_Name WHERE Condition;
Examples:-
Selecting All Rows in a Table:-
SQL> SELECT * FROM Client_Master;
CLIENT_NO CLIENT_NAME
ADDRESS
CITY STATE PINCODE
BALANCE_DUE
------------------- ------------------------- ------------------------------ ---------- ----------- -------------- ------------------------C00001 Ivan Bayross No 15, Vasanth Vihar Mumbai Maharashtra 400054
15000
C00002 Basu Navidngi 27,Heritage Apmts
Mumbai Maharashtra 400056
10000
C00003 Ravi Sreedharan
18,Luxury Street
Delhi New Delhi 100001
2000
3 rows selected.
Select Particular Rows of a Table:-
SQL> SELECT Client_No, Client_Name, Balance_Due FROM
Client_Master;
PPPA
A
G
E
O
AG
GE
E 333 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
CLIENT_NO
CLIENT_NAME
------------------------------------------C00001
Ivan Bayross
C00002
Basu Navidngi
C00003
Ravi Sreedharan
BALANCE_DUE
------------------------15000
10000
2000
3 rows selected.
Select Rows that Satisfies a Condition:-
SQL> SELECT Client_No, Client_Name, Balance_Due FROM Client_Master
2
WHERE Balance_Due > 5000;
CLIENT_NO
CLIENT_NAME
BALANCE_DUE
------------------------------------------------------------------C00001
Ivan Bayross
15000
C00002
Basu Navidngi
10000
2 rows selected.
UPDATE Command:
UPDATE Command is used for the following,
A)
B)
Update All Rows In a Table,
Update Particular Rows of a Table.
-------------------------------------------------------------------------------------------------------
Syntax:-
A)
Updating All Rows of a Table:UPDATE Table_Name
SET Column_Name = EXPRESSION,
Column_Name = EXPRESSION,
..... ;
PPPA
A
G
E
O
AG
GE
E 444 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
B)
Updating Particular Rows of a Table:UPDATE Table_Name
SET Column_Name = EXPRESSION,
Column_Name = EXPRESSION, . . .
..
WHERE Column_Name = EXPRESSION;
Examples:A)
SQL>
Updating All Rows of a Table:-
UPDATE Emp_Master
2
SET Net_Sal = Basic_Sal + Basic_Sal *
1.15;
2 rows updated.
SQL> SELECT * FROM Emp_Master;
EMP_NO EMP_NAME DEPARTMENT BASIC_SAL NET_SAL
--------------- --------------------- ------------------------ ------------------ --------------E00001
Rukmini
Sales
10000
11500
E00001
Cynthia
Purchase
12000
13800
2 rows selected.
B)
Updating Particular Rows of a Table:-
SQL>
UPDATE Emp_Master
2
SET Net_Sal = Basic_Sal + Basic_Sal *
1.15
WHERE Emp_No = ‘E00003’;
3
1 row updated.
SQL> SELECT * FROM Emp_Master;
EMP_NO EMP_NAME DEPARTMENT BASIC_SAL NET_SAL
--------------- --------------------- ------------------------ ------------------ --------------E00001
Rukmini
Sales
10000
11500
E00001
Cynthia
Purchase
12000
13800
E00003
Clara
Accounts
21000
24150
3 rows selected.
PPPA
A
G
E
O
AG
GE
E 555 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
DELETE Command:
DELETE Command is used for the following,
A)
B)
Delete All Rows In a Table,
Delete Particular Rows of a Table.
---------------------------------------------------------------------------------------------------------------------------------------------
Syntax:-
A)
Deleting All Rows of a Table:-
DELETE FROM Table_Name;
B)
Updating Particular Rows of a Table:DELETE FROM Table_Name
WHERE SEARCH_CONDITION;
Examples:A)
SQL>
Deleting All Rows of a Table:-
DELETE FROM Emp_Master;
3 rows deleted.
SQL> SELECT * FROM Emp_Master;
no rows selected.
PPPA
A
G
E
O
AG
GE
E 666 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
B)
Deleting Particular Rows of a Table:-
SQL>
DELETE FROM Emp_Master
2
WHERE Emp_No = ‘E00003’;
1 row deleted.
SQL> SELECT * FROM Emp_Master;
EMP_NO EMP_NAME DEPARTMENT BASIC_SAL NET_SAL
--------------- --------------------- ------------------------ ------------------ --------------E00001
Rukmini
Sales
10000
11500
E00001
Cynthia
Purchase
12000
13800
2 rows selected.
PPPA
A
G
E
O
AG
GE
E 777 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
DDL COMMANDS
=============================================================
The Commands that are listed under Data Definition Language(DDL) are,
CREATE Command,
ALTER Command,
DROP Command.
=============================================================
PPPA
A
G
E
O
AG
GE
E 888 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
CREATE Command:
CREATE Command is used for the following,
Creating A Table,
Creating An Index,
Creating A View.
------------------------------------------------------------------------------------------------------Creating A Table:
Create a New Table,
Create a New Table from an Existing Table.
Syntax:Create a New Table:
CREATE TABLE table_name
(
Column_Name Data_Type(Size),
Column_Name Data_Type(Size),
.....
);
Creating Table From a Table:
CREATE TABLE table_name
(
Column_Name, Column_Name, …
AS SELECT
Column_Name, Column_Name, …
FROM table_name;
Examples:Create a New Table:
SQL> CREATE TABLE Client_Master
2
(
3
Client_No varchar2(6),
4
Client_Name varchar2(20),
5
Address varchar2(30),
6
City varchar2(15),
7
State varchar2(15),
8
Pincode number(6),
9
Balance_Due number(12,2)
10
);
Table created.
PPPA
A
G
E
O
AG
GE
E 999 O
OFFF 777222
)
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
Table Description:SQL> DESCRIBE Client_Master;
Name
Null?
Type
------------------------------- ------------- --------------------CLIENT_NO
VARCHAR2(6)
CLIENT_NAME
VARCHAR2(20)
ADDRESS
VARCHAR2(30)
CITY
VARCHAR2(15)
STATE
VARCHAR2(15)
PINCODE
NUMBER(6)
BALANCE_DUE
NUMBER(12,2)
Creating Table From a Table:
SQL> CREATE TABLE Supplier_Master
2
(
3
Supplier_No, Supplier_Name, Address, City, State, Pincode
4
)
5
AS SELECT
6
Client_No, Client_Name, Address, City, State, Pincode
7
From Client_Master;
Table created.
Table Description:SQL> DESCRIBE Supplier_Master;
Name
Null?
Type
---------------------------------- ------------- -----------------------SUPPLIER_NO
VARCHAR2(6)
SUPPLIER_NAME
VARCHAR2(20)
ADDRESS
VARCHAR2(30)
CITY
VARCHAR2(15)
STATE
VARCHAR2(15)
PINCODE
NUMBER(6)
PPPA
A
G
E
O
AG
GE
E 111000 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
Creating An Index:
Oracle allows the Creation of Two types of Indexes. These are:
Indexes that Allow Duplicate values for the Indexed columns.
i.e., Duplicate Index.
Indexes that Deny Duplicate values for the Indexed columns.
i.e., Unique Index.
Creation Of Index:
An Index can be Created on One or More Columns. Based on the number of Columns
inckuded in the Index, an Index can be:
Simple Index
Composite Index
Creating Simple Index (Allows Duplicate Values),
Creating Composite Index (Allows Duplicate Values),
Creation Of Simple Unique Index,
Creation Of Composite Unique Index.
Syntax:-
Simple Index (With Duplication):CREATE INDEX Index_Name
ON Table_Name(Column_Name);
Composite Index (With Duplication):CREATE INDEX Index_Name
ON Table_Name
(Column_Name, Column_Name, .....);
Simple Unique Index:CREATE UNIQUE INDEX Index_Name
ON Table_Name(Column_Name);
PPPA
A
G
E
O
AG
GE
E 111111 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
Composite Unique Index:CREATE UNIQUE INDEX Index_Name
ON Table_Name
(Column_Name, Column_Name, .....);
Examples:-
(i)
Simple Index (With Duplication):-
SQL> CREATE INDEX idx_client_no
2
ON Client_Master(Client_No);
Index created.
(ii)
Composite Index (With Duplication):-
SQL> CREATE INDEX idx_sales_order_details
2
ON Sales_Order_Details(Order_No, Product_No);
Index created.
(iii)
Simple Unique Index:-
SQL> CREATE UNIQUE INDEX indx_client_name
2
ON Client_Master(Client_Name);
Index created.
(iv)
Composite Unique Index:-
SQL> CREATE UNIQUE INDEX indx_prdt_price
2
ON Product_Master(Sell_price, Cost_Price);
Index created.
PPPA
A
G
E
O
AG
GE
E 111222 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
Creating A View:
Syntax:CREATE VIEW View_Name AS
SELECT Column_Name, Column_Name
FROM Table_Name
WHERE Column_Name = Expression List;
GROUP BY Grouping Criteria
HAVING Predicate
Examples:-
SQL> CREATE VIEW vw_client AS
2
SELECT Client_No, Client_Name, State,
3
Pincode, Balance_Due
4
FROM Client_Master;
View created.
SQL> select * From vw_client;
CLIENT_NO CLIENT_NAME STATE
PINCODE BALANCE_DUE
-------------------- ------------------------- ---------------------- --------------- -----------------------C00001
Ivan Bayross
Maharashtra 400054
15000.00
C00002
Basu Navindgi
Maharashtra 400056
10000.00
C00003
Ravi Sreedaran New Delhi
100001
2000.00
3 rows selected.
PPPA
A
G
E
O
AG
GE
E 111333 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
------------------------------------------------------------------------------------------------------ALTER Command:
ALTER Command is used for the following,
Add New Columns, Constraints to a Table,
Modify Existing Columns, Constraints of a Table,
To Drop a Constraint From a Table.
------------------------------------------------------------------------------------------------------Syntax:Add New Columns, Constraints to a Table:
Add New Columns to a Table:ALTER TABLE Table_Name
ADD ( New_Column_Name DataType(Size),
New_Column_Name DataType(Size),
.....
);
Add New Constraints to a Table:ALTER TABLE Table_Name
ADD Constraint_Name(Column_Name);
Examples:-
Table Description Before Alteration:
SQL> DESCRIBE Supplier_Master;
Name
Null? Type
----------------------------------- -------- ---------------------------SUPPLIER_NO
VARCHAR2(6)
SUPPLIER_NAME
VARCHAR2(20)
ADDRESS
VARCHAR2(30)
CITY
VARCHAR2(15)
STATE
VARCHAR2(15)
PINCODE
NUMBER(6)
PPPA
A
G
E
O
AG
GE
E 111444 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
Add New Columns to a Table:-
SQL> ALTER TABLE Supplier_Master
2
ADD( Phone_No number(10), Fax_No number(15) );
Table altered.
SQL> DESCRIBE Supplier_Master;
Name
Null? Type
--------------------------------- -------- -------------------SUPPLIER_NO
VARCHAR2(6)
SUPPLIER_NAME
VARCHAR2(20)
ADDRESS
VARCHAR2(30)
CITY
VARCHAR2(15)
STATE
VARCHAR2(15)
PINCODE
NUMBER(6)
PHONE_NO
NUMBER(10)
FAX_NO
NUMBER(15)
Add New Constraints to a Table:SQL> ALTER TABLE Supplier_Master
2
ADD PRIMARY KEY(Supplier_No);
Table altered.
SQL> DESCRIBE Supplier_Master;
Name
Null?
Type
------------------------------------ ------------------ -------------------SUPPLIER_NO
NOT NULL VARCHAR2(6)
SUPPLIER_NAME
VARCHAR2(20)
ADDRESS
VARCHAR2(30)
CITY
VARCHAR2(15)
STATE
VARCHAR2(15)
PINCODE
NUMBER(6)
PHONE_NO
NUMBER(10)
FAX_NO
NUMBER(15)
PPPA
A
G
E
O
AG
GE
E 111555 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
Syntax:Modify Existing Columns, Constraints to a Table:
Modify Existing Columns to a Table:ALTER TABLE Table_Name
MODIFY ( Column_Name New_DataType(New_Size),
Column_Name New_DataType(New_Size),
.....
);
Add New Constraints to a Table:ALTER TABLE Table_Name
MODIFY ( Column_Name DataType(Size) Constraint_Name);
Examples:-
Table Description Before Alteration:
SQL> DESCRIBE Supplier_Master;
Name
Null? Type
----------------------------------- -------- ---------------------------SUPPLIER_NO
VARCHAR2(6)
SUPPLIER_NAME
VARCHAR2(20)
ADDRESS
VARCHAR2(30)
CITY
VARCHAR2(15)
STATE
VARCHAR2(15)
PINCODE
NUMBER(6)
PHONE_NO
NUMBER(10)
FAX_NO
NUMBER(15)
Add New Columns to a Table:-
SQL> ALTER TABLE Supplier_Master
2
MODIFY( Fax_No number(25) );
Table altered.
PPPA
A
G
E
O
AG
GE
E 111666 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
SQL> DESCRIBE Supplier_Master;
Name
Null? Type
--------------------------------- -------- -------------------SUPPLIER_NO
VARCHAR2(6)
SUPPLIER_NAME
VARCHAR2(20)
ADDRESS
VARCHAR2(30)
CITY
VARCHAR2(15)
STATE
VARCHAR2(15)
PINCODE
NUMBER(6)
PHONE_NO
NUMBER(10)
FAX_NO
NUMBER(25)
Add New Constraints to a Table:SQL> ALTER TABLE Supplier_Master
2
MODIFY ( SUPPLIER_NAME varchar2(20)
NOT NULL);
Table altered.
SQL> DESCRIBE Supplier_Master;
Name
Null?
Type
------------------------------------ ------------------ -------------------SUPPLIER_NO
NOT NULL VARCHAR2(6)
SUPPLIER_NAME
NOT NULL VARCHAR2(20)
ADDRESS
VARCHAR2(30)
CITY
VARCHAR2(15)
STATE
VARCHAR2(15)
PINCODE
NUMBER(6)
PHONE_NO
NUMBER(10)
FAX_NO
NUMBER(15)
To Drop a Constraint From a Table:Syntax:ALTER TABLE Supplier_Master
DROP Constraint_Name;
Example:SQL> ALTER TABLE Supplier_Master
2
DROP PRIMARY KEY;
Table altered.
PPPA
A
G
E
O
AG
GE
E 111777 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
DROP Command:
DROP Command is used for the following,
To Drop a Table,
To Drop an Index,
To Drop a View.
--------------------------------------------------------------------------------------------------------------------------------------------Syntax:To Drop a Table:DROP TABLE Table_Name;
To Drop an Index:DROP INDEX Index_Name;
To Drop A View:DROP VIEW View_Name;
Examples:To Drop a Table:SQL> DROP TABLE Product_Master;
Table dropped.
To Drop an Index:SQL> DROP INDEX idx_client_no;
Index dropped.
To Drop A View:SQL> DROP VIEW vw_client;
View dropped.
PPPA
A
G
E
O
AG
GE
E 111888 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
DCL COMMANDS
=============================================================
The Commands that are listed under Data Control Language(DCL) are,
GRANT Command,
REVOKE Command.
=============================================================
PPPA
A
G
E
O
AG
GE
E 111999 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
GRANT Command:
GRANT Command is used to Grant Access of the
Objects belonging to a user to whomever he / she wishes to
permit to access them.
-------------------------------------------------------------------------------------------------------
Syntax:GRANT {Object Privileges}
ON Object_Name
TO User_Name
[ WITH GRANT OPTION ];
Examples:-
SQL>
(i)
GRANT ALL
ON Product_Master
TO Pradeep;
SQL>
SQL>
(ii)
GRANT SELECT, UPDATE
ON Client_Master
TO Mita;
(iii)
GRANT ALL
ON Client_Master
TO Ivan
WITH GRANT OPTION;
REVOKE Command:
REVOKE Command is used to Revoke Access of the
Objects Granted to another user. Apart from the Owner, a
User who has been granted the Grant Privilege can Revoke
privileges from others.
------------------------------------------------------------------------------------------------------PPPA
A
G
E
O
AG
GE
E 222000 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
Syntax:REVOKE {Object Privileges}
ON Object_Name
FROM User_Name;
Examples:-
SQL>
SQL>
SQL>
(i)
REVOKE ALL
ON Product_Master
FROM Pradeep;
(ii)
REVOKE SELECT
ON Client_Master
FROM Mita;
(iii)
REVOKE DELETE
ON Client_Master
FROM Ivan;
PPPA
A
G
E
O
AG
GE
E 222111 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
Looping &
Conditional
Statements
Conditional Control Statements:
=============================================================
PL/SQL allows the use of IF Statement to control the execution of a
block of code. In PL/SQL, the IF – THEN – ELSIF – END IF construct in
code blocks allow specifying certain conditions under which a specific
block of code should be executed.
=============================================================
PPPA
A
G
E
O
AG
GE
E 222222 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
Syntax:IF < Condition > THEN
< Action >
ELSIF < Condition > THEN
< Action >
ELSE
< Action >
END IF;
Example 1:
Write a PL/SQL code block that will accept an account number from the user and
debit an amount of Rs. 2000 from the account if the account has a
minimum balance of 500 after the amount is debited. The process
is to be fired on the Accounts Table.
SQL>
SELECT * FROM Accounts;
ACCOUNT_ID
---------------------AC001
AC002
AC003
AC004
AC005
NAME
------------Anuj
Robe
Mita
Sunita
Melba
BALANCE
---------------5000
10000
5000
15000
10000
5 rows selected.
SQL> SET SERVEROUTPUT ON;
2
3
4
5
6
7
8
9
10
11
SQL> DECLARE
/* Declaration of Memory Variables and Constants to be used in the
Executable section. */
Acct_Balance number(11,2);
Acct_No varchar2(6);
Acct_Name varchar2(20);
Debit_Amt number(5) := 2000;
Min_Bal CONSTANT number(5,2) := 500.00;
BEGIN
PPPA
A
G
E
O
AG
GE
E 222333 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/* Accept an Account No from the User */
Acct_No := &Acct_No;
/* Retrieving the Balance from the Accounts Table where Account
No in the Table is Equal to the Account No entered by the User. */
SELECT Name, Balance INTO Acct_Name, Acct_Balance
FROM Accounts
WHERE Account_Id = Acct_No;
DBMS_OUTPUT.PUT_LINE('Existing Record');
DBMS_OUTPUT.PUT_LINE('Account Number: ' || Acct_No);
DBMS_OUTPUT.PUT_LINE('Account Holder Name: ' ||
Acct_Name);
DBMS_OUTPUT.PUT_LINE('Balance IN Account: ' ||
Acct_Balance);
/* Subtract an Amount of Rs. 2000 from the Balance retrieved
from
the table */
Acct_Balance := Acct_Balance - Debit_Amt;
/* Checking if the Resultant Balance is greater than or equal to
the
minimum balance of Rs. 500. If the condition is satisfied an
amount
of Rs. 2000 is Subtracted from the Balance of the
corresponding
Account No. */
IF Acct_Balance >= Min_Bal THEN
UPDATE Accounts SET Balance = Balance - Debit_Amt
WHERE Account_Id = Acct_No;
END IF;
DBMS_OUTPUT.PUT_LINE('After Updating Record');
DBMS_OUTPUT.PUT_LINE('Account Number: ' || Acct_No);
DBMS_OUTPUT.PUT_LINE('Account Holder Name: ' ||
Acct_Name);
DBMS_OUTPUT.PUT_LINE('Balance IN Account: ' ||
Acct_Balance);
END;
/
PPPA
A
G
E
O
AG
GE
E 222444 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
Enter value for acct_no: 'AC003'
old 15: Acct_No := &Acct_No;
new 15: Acct_No := 'AC003';
Existing Record
Account Number: AC003
Account Holder Name: Mita
Balance IN Account: 5000
After Updating Record
Account Number: AC003
Account Holder Name: Mita
Balance IN Account: 3000
PL/SQL procedure successfully completed.
SQL>
ACCOUNT_ID
---------------------AC001
AC002
AC003
AC004
AC005
SELECT * FROM Accounts;
NAME
------------Anuj
Robe
Mita
Sunita
Melba
BALANCE
---------------5000
10000
3000
15000
10000
5 rows selected.
Example 2:
Write a PL/SQL block of code to achieve the following: If the Price of a
Product is less than 4000, then change the Price to 4000.
The Change must be recorded in the Table too.
SQL> SELECT * FROM Product_Details;
PRODUCT_NO SELL_PRICE
------------------------ -------------------P00001
3200
P00002
3400
P00003
3000
P00004
1500
P00005
2000
5 rows selected.
PPPA
A
G
E
O
AG
GE
E 222555 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
SQL>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
DECLARE
/* Declaration of Memory variables and constants to be
used
in the Execution Section. */
Product_Id varchar2(6);
Selling_Price number(8,2);
BEGIN
/* Accept a Product Id from the User. */
Product_Id := '&Product_Id';
SELECT Sell_Price INTO Selling_Price
FROM Product_Details
Where Product_No = Product_Id;
/* If the Sell Price is less than 4000, Update it to 4000. */
IF Selling_Price < 4000 THEN
UPDATE Product_Details
SET Sell_Price = 4000
22
23
24
25
26
WHERE Product_No = Product_Id;
INSERT INTO Old_Price_Table
( Product_No, Date_Change, Old_Price)
VALUES ('P00001',sysdate,Selling_Price);
DBMS_OUTPUT.PUT_LINE(' The New Price Of '
||
27
28
29
30
31
32
33
Product_Id || ' Is: 4000');
ELSE
DBMS_OUTPUT.PUT_LINE('Current Price Of ' ||
Product_Id || ' Is: ' || Selling_Price );
END IF;
END;
/
Enter value for product_id: P00002
old 11: Product_Id := '&Product_Id';
new 11: Product_Id := 'P00002';
The New Price Of P00002 Is: 4000
PL/SQL procedure successfully completed.
SQL>
SELECT * FROM Product_Details;
PPPA
A
G
E
O
AG
GE
E 222666 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
PRODUCT_NO
SELL_PRICE
------------------------------------------P00001
3200
P00002
4000
P00003
3000
P00004
1500
P00005
2000
5 rows selected.
SQL>
SELECT * FROM Old_Price_Table;
PRODUCT_NO DATE_CHANGED OLD_PRICE
------------------------ ---------------------------------------------P00001
10-JAN-08
3400
1 row selected.
PPPA
A
G
E
O
AG
GE
E 222777 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
Iterative Control
Statement
=============================================================
Iterative Control indicates the ability to Repeat or Skip sections of a
Code Block. A Loop marks a Sequence of Statements that
has to be repeated.
The Keyword LOOP has to be placed
before the first statement in the sequence of statements to be
repeated, while the keyword END LOOP is placed
immediately after the last statement in the Sequence.
=============================================================
PPPA
A
G
E
O
AG
GE
E 222888 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
The WHILE Loop:
Syntax:WHILE < Condition >
LOOP
< Action >
END LOOP;
Example 1:
Write a PL/SQL code block to calculate the Area of a circle for a value of
Radius varying from 3 to 7. Store the Radius and the
corresponding values of calculated Area in a Table, Areas.
SQL>
2
3
4
5
CREATE TABLE Areas
(
Radius number(2),
Area number(6,2)
);
Table created.
SQL>
2
3
4
5
6
7
8
9
10
11
12
13
DECLARE
/* Declaration of Memory variables and constants to be
used in the Execution section. */
Pi constant number(4,2) := 3.14;
Radius number(2);
Area number(6,2);
BEGIN
/* Initialize the Radius to 3, since calculations are required
for Radius 3 to 7. */
Radius := 3;
/* Set a Loop so that it fires till the Radius value reaches 7.
*/
14
15
16
17
18
19
20
21
22
WHILE Radius <= 7
LOOP
/* Area calculation for a Circle */
Area := Pi * POWER(Radius,2);
/* Insert the value for the Radius and its
corresponding Area calculated in the Table.
*/
23
PPPA
A
G
E
O
AG
GE
E 222999 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
24
25
26
27
INSERT INTO Areas
VALUES ( Radius, Area );
/* Increment the value of the variable Radius by 1
*/
28
29
30
31
32
Radius := Radius + 1;
END LOOP;
END;
/
PL/SQL procedure successfully completed.
SQL>
RADIUS
------------3
4
5
6
7
SELECT * FROM Areas;
AREA
----------28.26
50.24
78.5
113.04
153.86
5 rows selected.
Example 2:
SQL>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
DECLARE
/* Declaration of Memory variables and constants to be
used in the Execution Section. */
Value number(5);
Res_Val number;
BEGIN
/* Initialize the value to 12345, Since calculations are
required from 12345 to 12385. */
Value := 12345;
/* Set a LOOP so that it fires till Value reaches 12385. */
WHILE Value <= 12385
LOOP
Res_Val := Value;
WHILE Value > 9
LOOP
Value := (MOD(Value,10) + FLOOR(Value /
10));
PPPA
A
G
E
O
AG
GE
E 333000 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
22
END LOOP;
23
24
INSERT INTO Sum_Of_Digits VALUES
25
( Res_Val, Value );
26
Value := Res_Val + 10;
27
END LOOP;
28
END;
29
/
PL/SQL procedure successfully completed.
SQL>
SELECT * FROM Sum_Of_Digits;
VALUE
SUM_VALUE
------------- ---------------------12345
6
12355
7
12365
8
12375
9
12385
1
The FOR Loop:
Syntax:-
FOR variable IN [REVERSE] start .. end
LOOP
< Action >
END LOOP;
Example 1:
Write a PL/SQL block of code for Inverting a number
5639 to 9365.
SQL>
2
3
4
5
6
7
8
9
DECLARE
/* Declaration of Memory variables and Constants to be
used in the Execution Section. */
Given_Number varchar2(5) := '5639';
Str_Length number(2);
Inverted_Number varchar2(5);
BEGIN
/* Store the Length of the given number. */
PPPA
A
G
E
O
AG
GE
E 333111 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
10
11
12
13
Str_Length := LENGTH(Given_Number);
/* Initialize the Loop such that it repeats for the
number
14
15
16
17
18
19
20
21
22
23
24
25
26
of times equal to the Length of the given number.
Also, since the number is required to be inverted,
the loop should consider the last number first and
store it, i.e., in Reverse Order. */
FOR cntr IN REVERSE 1 .. STR_Length
/* Variabls used as Counter in for loop need not be
declared
i.e., cntr declaration is not required. */
LOOP
/* The Last Digit is obtained using the SUBSTR
Function,
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
and stored in a variable, while retaining the
previous digit stored in the variable. */
Inverted_Number := Inverted_Number ||
SUBSTR(Given_Number,cntr,1);
END LOOP;
/* Display the Initial number, as well as the inverted
number,
which is stored in the variable on screen. */
DBMS_OUTPUT.PUT_LINE('The Given Number is: ' ||
Given_Number);
DBMS_OUTPUT.PUT_LINE('The Inverted Number is: ' ||
Inverted_Number);
END;
/
The Given Number is: 5639
The Inverted Number is: 9365
PL/SQL procedure successfully completed.
PPPA
A
G
E
O
AG
GE
E 333222 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
Example 2:
Write a PL/SQL block to generate Fibonacci Series.
SQL>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
DECLARE
/* Declaration of Memory Variables and Constants to
be used in the Execution Section. */
N number(2);
F1 number(3) := -1;
F2 number(3) := 1;
F3 number(3);
BEGIN
/* Accept N Value from the User. */
N := &N;
/* Initialize the Loop such that it repeats for N Times. */
FOR cntr IN 1 .. N
/* Variables used as counter in FOR Loop need not be
declared. */
LOOP
/* F1 and F2 are added and stored in F3.
Then Value in F2 is shifted to F1 &
Value in F3 is shifted to F2. */
F3 := F1 + F2;
INSERT INTO Fibonacci VALUES
( cntr, F1, F2, F3 );
F1 := F2;
F2 := F3;
END LOOP;
/* Display the End Value in F3 after N iterations. */
DBMS_OUTPUT.PUT_LINE('The Value in F3 is: ' || F3);
END;
PPPA
A
G
E
O
AG
GE
E 333333 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
40
/
Enter value for n: 10
old 12: N := &N;
new 12: N := 10;
SP2-0317: expected symbol name is missing
The Value in F3 is: 34
PL/SQL procedure successfully completed.
SQL> SELECT * FROM Fibonacci;
ITERATION
------------------1
2
3
4
5
6
7
8
9
10
F1
F2
F3
---------- ---------- ----------1
1
0
1
0
1
0
1
1
1
1
2
1
2
3
2
3
5
3
5
8
5
8
13
8
13
21
13
21
34
10 rows selected.
PPPA
A
G
E
O
AG
GE
E 333444 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
PL/SQL
PROGRAMS
=============================================================
As the name suggests, PL/SQL is a superset of SQL. PL/SQL is a blockstructured language that enables developers to combine power
of SQL with procedural statements. PL/SQL bridges the gap
between database technology and procedural programming
languages.
=============================================================
PPPA
A
G
E
O
AG
GE
E 333555 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
Syntax:-
DECLARE
Procedural Statements;
BEGIN
Procedural Statements;
SQL Statements;
EXCEPTIONS
SQL Statements;
END;
Example 1:
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
2
Acct_No varchar2(6);
3
Acct_Name varchar2(20);
4
Acct_Balance number(10,2);
5
BEGIN
6
Acct_No := '&Acct_No';
7
SELECT Name, Balance INTO Acct_Name, Acct_Balance
8
FROM Accounts
9
WHERE Account_Id = Acct_No;
10
DBMS_OUTPUT.PUT_LINE('Account Number: ' || Acct_No);
11 DBMS_OUTPUT.PUT_LINE('Account Holder Name: ' || Acct_Name);
12 DBMS_OUTPUT.PUT_LINE('Balance IN Account: ' || Acct_Balance);
13
End;
14
/
Enter value for acct_no: AC002
old 6: Acct_No := '&Acct_NO';
new 6: Acct_No := 'AC002';
Account Number: AC002
Account Holder Name: Robert
Balance IN Account: 10000
PL/SQL procedure successfully completed.
Example 2:
SQL> SET SERVEROUTPUT ON;
PPPA
A
G
E
O
AG
GE
E 333666 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
SQL>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
DECLARE
/* Declaration of Memory variables and Constants to be used
in the Execution Section. */
Acc_Id varchar2(10);
Accr_Name varchar2(20);
Deposit number(10,2);
Withdraw number(10,2);
Bal number(12,2);
BEGIN
/* Accept an Account No From the User */
Acc_Id := '&Acc_Id';
/* Retrieve the Balance from the Bank Account Table. */
SELECT Balance INTO Bal
FROM Bank_Account
WHERE Acc_No = Acc_Id;
/* Accept Deposit Amount Amount from the User. */
Deposit := &Deposit;
/* Add Deposit to Balance And
Store Both Values In the Table. */
UPDATE Bank_Account
SET Balance = Balance + Deposit,
Last_Deposit = Deposit
WHERE Acc_No = Acc_Id;
DBMS_OUTPUT.PUT_LINE('After Updating Record');
DBMS_OUTPUT.PUT_LINE('Account No: ' || Acc_Id);
DBMS_OUTPUT.PUT_LINE('Deposit Amt: ' || Deposit);
/* Accept Withdraw Amount Amount from the User. */
Withdraw := &Withdraw;
/* Subtract Withdraw from Balance And
Store Both Values In the Table. */
UPDATE Bank_Account
SET Balance = Balance - Withdraw,
Last_Withdrawal = Withdraw
WHERE Acc_No = Acc_Id;
PPPA
A
G
E
O
AG
GE
E 333777 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
50
51
52
53
54
55
DBMS_OUTPUT.PUT_LINE('After Updating Record');
DBMS_OUTPUT.PUT_LINE('Account No: ' || Acc_Id);
DBMS_OUTPUT.PUT_LINE('Withdraw Amt: ' || Withdraw);
END;
/
Enter value for acc_id: ACC001
old 14: Acc_Id := '&Acc_Id';
new 14: Acc_Id := 'ACC001';
Enter value for deposit: 4000.50
old 24: Deposit := &Deposit;
new 24: Deposit := 4000.50;
Enter value for withdraw: 2000.25
old 40: Withdraw := &Withdraw;
new 40: Withdraw := 2000.25;
After Updating Record
Account No: ACC001
Deposit Amt: 4000.5
After Updating Record
Account No: ACC001
Withdraw Amt: 2000.25
PL/SQL procedure successfully completed.
SQL>
SELECT * FROM Bank_Account;
ACC_NO
ACC_NAME
LAST_DEPOSIT LAST_WITHDRAWAL
BALANCE
-------------- ------------------------------- ---------------------------------------------------------- ---------------ACC001
Sasi Kumar
4000.5
2000.25
11001.2
ACC002
Prakash
2000
1000
2000.95
ACC003
Manikandan
2500
1500
5000.95
ACC004
Akshaya Lakshmi
6000
5000
8000.95
ACC005
Janaki Raman
5500
2500
11000.95
5 rows selected.
PPPA
A
G
E
O
AG
GE
E 333888 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
EXCEPTIONS
=============================================================
When an SQL sentence fails the Oracle engine is the first to recognize this as
an EXCEPTION CONDITION. The Oracle engine immediately
tries to handle the exception condition and resolve it. This is
done by raising a built-in Exception Handler.
=============================================================
PPPA
A
G
E
O
AG
GE
E 333999 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
Pre-Defined Exception Handlers:
Syntax:EXCEPTION
WHEN { Exception Name } THEN
{ User Defined action to be carried out }
Example :SQL>
SELECT * FROM Salesman_Master;
SALESMAN_NO SALESMAN_NAME COMMISSION TGT_TO_GET
YTD_SALES
------------------------- ----------------------------- ---------------------- -----------------------------------S00001
Kiran
5
100
50
S00002
Manish
4
200
300
S00003
Ravi
3
200
350
S00004
Ashish
7
200
150
4 rows selected.
SQL>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
DECLARE
Sman_No Salesman_Master.Salesman_No%TYPE;
Sales_Amt Salesman_Master.Ytd_Sales%TYPE;
Comm_Rate Salesman_Master.Commission%TYPE;
BEGIN
/* Retrieving records from the Salesman Master table
and Assigning them to Memory variables for the
Salesman No entered by the User. */
SELECT Salesman_No, Commission, Ytd_Sales
INTO Sman_No, Comm_Rate, Sales_Amt
FROM Salesman_Master
WHERE Salesman_No = '&Salesman_No';
/* Calculating the commission amount payable
PPPA
A
G
E
O
AG
GE
E 444000 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
19
20
21
22
and inserting into the Commission payable table. */
INSERT INTO Commission_Payable
VALUES (Sman_No, sysdate, Sales_Amt * Comm_Rate /
100);
23
24
25
26
27
28
29
30
31
32
33
34
35
36
EXCEPTION
/* Using the Oracle engine's named Exception
handler to handle the error condition that may occur
if the user enters a Salesman No that is not present
in the Salesman Master Table */
WHEN no_data_found THEN
DBMS_OUTPUT.PUT_LINE('Salesman No ' ||
Sman_No
|| ' is not present in the Salesman Master table ');
END;
/
Enter value for salesman_no: S00006
old 16:
WHERE Salesman_No = '&Salesman_No';
new 16:
WHERE Salesman_No = 'S00006';
Salesman No is not present in the Salesman Master table
PL/SQL procedure successfully completed.
User – Defined Exception Handlers:
Syntax:DECLARE
< Exception Name > Exception;
BEGIN
SQL Sentence;
IF < Condition > THEN
RAISE < Exception Name >;
END IF;
EXCEPTION
WHEN < Exception Name > THEN
{ User defined action to be taken } ;
END;
PPPA
A
G
E
O
AG
GE
E 444111 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
Example :-
SQL>
SELECT * FROM Salesman_Master;
SALESMAN_NO SALESMAN_NAME COMMISSION TGT_TO_GET
YTD_SALES
------------------------- ----------------------------- ---------------------- -----------------------------------S00001
Kiran
5
100
50
S00002
Manish
4
200
300
S00003
Ravi
3
200
350
S00004
Ashish
7
200
150
4 rows selected.
SQL>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
DECLARE
Less_Than_Target EXCEPTION;
Sman_No Salesman_Master.Salesman_No%TYPE;
Tgt_Sales Salesman_Master.Tgt_To_Get%TYPE;
Act_Sales Salesman_Master.Ytd_Sales%TYPE;
Comm_Rate Salesman_Master.Commission%TYPE;
BEGIN
/* Retrieving records from the Salesman Master table
and Assigning them to Memory variables for the
Salesman No entered by the User. */
SELECT Salesman_No, Commission, Tgt_To_Get,
Ytd_Sales
INTO Sman_No, Comm_Rate, Tgt_Sales, Act_Sales
FROM Salesman_Master
WHERE Salesman_No = '&Salesman_No';
IF Act_Sales < Tgt_Sales THEN
RAISE Less_Than_Target;
PPPA
A
G
E
O
AG
GE
E 444222 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
23
24
25
26
ELSE
/* Calculating the commission amount payable
and inserting into the Commission payable
table. */
27
28
29
30
31
32
33
34
35
36
37
38
39
40
INSERT INTO Commission_Payable
VALUES
(Sman_No,sysdate,Act_Sales*Comm_Rate/100);
END IF;
EXCEPTION
WHEN Less_Than_Target THEN
DBMS_OUTPUT.PUT_LINE('Salesman No ' || Sman_No
|| ' is not entitled to get commission ');
END;
/
Enter value for salesman_no: S00001
old 18:
WHERE Salesman_No = '&Salesman_No';
new 18:
WHERE Salesman_No = 'S00001';
Salesman No S00001 is not entitled to get commission
PL/SQL procedure successfully completed.
SQL> /
Enter value for salesman_no: S00002
old 18:
WHERE Salesman_No = '&Salesman_No';
new 18:
WHERE Salesman_No = 'S00002';
PL/SQL procedure successfully completed.
SQL>
SELECT * FROM Commission_Payable;
SMAN_NO COMM_DATE COMMISSION
------------------ ----------------------- -----------------------S00002
10-JAN-08
12
PPPA
A
G
E
O
AG
GE
E 444333 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
CURSORS
=============================================================
The Oracle Engine uses a work area for its internal processing in order to
execute an SQL statement. This work area is private to
SQL’s operations and is called a Cursor.
=============================================================
PPPA
A
G
E
O
AG
GE
E 444444 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
Syntax:Cursor Declaration:
CURSOR CursorName IS
SQL Select Statement;
Opening a Cursor:
OPEN CursorName;
Fetching Record from Cursor:
INTO Variable1, Variable2,…;
Closing a Cursor:
FETCH CursorName
CLOSE CursorName;
Example 1:
Write a PL/SQL Block that will display the Name, Department and Salary of
the first 5 employees getting the highest salary.
SQL>
SELECT * FROM Employee;
EMP_CODE E_NAME
DEPT_NO
JOB
SALARY
------------------- ----------------------------------- ------------------------------E00001
Sasi Kumar
20
Analyst
12000
E00002
Akshaya Lakshmi
20
Testing
10000
E00003
Janaki Raman
25
Officer
11000
E00004
Prakash
15
Shepherd
12345.99
E00005
Mani Kandan
20
Project Head
9000
E00006
Hari Haran
30
HP Salesman 8000
E00007
Ranjith
30
Bike Man
7000
7 rows selected.
SQL>
DEPT_NO
---------------20
20
25
15
20
30
30
SELECT * FROM Dept;
D_NAME
--------------Analyst
Testing
Officer
Shepherd
Project Head
HP Salesman
Bike Man
7 rows selected.
PPPA
A
G
E
O
AG
GE
E 444555 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
SQL>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
DECLARE
CURSOR C_Emp IS
SELECT E_Name, D_Name, Salary FROM
Employee,Dept
WHERE Dept.Dept_No = Employee.Dept_No
ORDER BY Salary DESC;
Str_Ename Employee.E_Name%TYPE;
Num_Dname Dept.D_Name%TYPE;
Num_Salary Employee.Salary%TYPE;
BEGIN
OPEN C_Emp;
DBMS_OUTPUT.PUT_LINE(' Name
Department
Salary ');
DBMS_OUTPUT.PUT_LINE(' --------- ------------------ --------- ');
LOOP
FETCH C_Emp INTO Str_Ename, Num_Dname,
Num_Salary;
exit when C_Emp%ROWCOUNT = 6 or
20
21
C_Emp%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(Str_Ename || '
22
||
23
24
25
26
Num_Dname || '
Num_Salary);
END LOOP;
END;
/
Name
Department
Salary
------------------------------ -----------------------------Prakash
Shepherd
12345.99
Sasi Kumar
Analyst
12000
Janaki Raman
Officer
11000
Akshaya Lakshmi Testing
10000
Mani Kandan
Project Head
9000
PL/SQL procedure successfully completed.
PPPA
A
G
E
O
AG
GE
E 444666 O
OFFF 777222
' ||
'
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
Example 2:
A HRD Manager has decided to raise the salary for all the Employees in
Department number 20 by 0.05 . Whenever any raise is given
to the employees, an audit trail of the same is maintained in
the Emp_Raise table. The Emp_Raise table holds the
employee number, the date when the raise was given and the
raise amount. Write a PL/SQL block to update the salary of
each employee of Dept_No 20 appropriately and insert a
record in the Emp_Raise table as well.
SQL>
SELECT * FROM Employee;
EMP_CODE E_NAME
DEPT_NO
JOB
SALARY
------------------- ----------------------------------- ------------------------------E00001
Sasi Kumar
20
Analyst
12000
E00002
Akshaya Lakshmi
20
Testing
10000
E00003
Janaki Raman
25
Officer
11000
E00004
Prakash
15
Shepherd
12345.99
E00005
Mani Kandan
20
Project Head
9000
E00006
Hari Haran
30
HP Salesman
8000
E00007
Ranjith
30
Bike Man
7000
7 rows selected.
SQL>
2
3
4
DECLARE
/* Declaration of the Cursor named C_Emp23
The active data set will include the Names,
Department,
PPPA
A
G
E
O
AG
GE
E 444777 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Department Numbers and Salaries of all Employes
belonging to Department 20. */
CURSOR C_Emp23 IS
SELECT Emp_Code, Salary FROM Employee
WHERE Dept_No = 20;
/* Declaration of Memory variable that holds data
Fetched from the Cursor. */
Str_Emp_Code Employee.Emp_Code%TYPE;
Num_Salary Employee.Salary%TYPE;
BEGIN
/* Opening Cursor C_Emp23. */
OPEN C_Emp23;
/* Infinite Loop to Fetch data from Cursor C_Emp23
One Row at a time. */
LOOP
FETCH C_Emp23 INTO Str_Emp_Code,
Num_Salary;
30
31
32
EXIT when
C_Emp23%NOTFOUND;
/* Updating the Salary in the Employee table as
Current
Salary +
Raise. */
33
34
35
UPDATE Employee
SET Salary = Num_Salary + ( Num_Salary
* 0.05 )
36
37
38
39
40
41
WHERE Emp_Code = Str_Emp_Code;
/* Insert a Record in the Emp_Raise table. */
INSERT INTO Emp_Raise
VALUES(Str_Emp_Code,sysdate,Num_Salary * 0.05);
42
43
44
45
END LOOP;
COMMIT;
PPPA
A
G
E
O
AG
GE
E 444888 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
46
47
48
49
50
/* Close Cursor C_Emp23. */
CLOSE C_Emp23;
END;
/
PL/SQL procedure successfully completed.
SQL>
SELECT * FROM Employee;
EMP_CODE E_NAME
DEPT_NO
JOB
SALARY
-------------------- -------------------------------- ---------------- ---------------------------------E00001
Sasi Kumar
20
Analyst
12600
E00002
Akshaya Lakshmi
20
Testing
10500
E00003
Janaki Raman
25
Officer
11000
E00004
Prakash
15
Shepherd
12345.99
E00005
Mani Kandan
20
Project Head
9450
E00006
Hari Haran
30
HP Salesman
8000
E00007
Ranjith
30
Bike Man
7000
7 rows selected.
SQL>
SELECT * FROM Emp_Raise;
EMP_CODE RAISE_DATE RAISE_AMT
------------------- ---------------------- -------------------E00001
10-JAN-08
600
E00002
10-JAN-08
500
E00005
10-JAN-08
450
PPPA
A
G
E
O
AG
GE
E 444999 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
TRIGGERS
=============================================================
Database triggers are database objects created via the SQL*PLUS tool on the
Client and stored on the Server in the Oracle engine’s system
table. These database objects consists of the following distinct
sections.
A named database event and
A PL/SQL block that will execute when the event occurs.
=============================================================
PPPA
A
G
E
O
AG
GE
E 555000 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
Syntax:-
CREATE OR REPLACE TRIGGER [Schema] TriggerName
{BEFORE, AFTER}
{DELETE, INSERT, UPDATE [OF Column, …]}
ON [Schema] TableName
[ REFERENCING { OLD AS Old, NEW AS New }]
[ FOR EACH ROW { WHEN Condition ] ]
DECLARE
Variable Declarations;
Constant Declarations;
BEGIN
PL/SQL SubProgram Body;
EXCEPTION
Exception PL/SQL Block;
END;
Example 1:
Create a transparent Audit system for a table Client_Master. The
system must keep track of the records that are being Deleted or Updated. The
Functionality being when a record is Deleted or
Modified the original record details and the Date of Operation
are stored in the Audit table, then the Delete or Update is
allowed to go through.
SQL>
2
SELECT Client_No, Client_Name, Bal_Due
FROM Client_Master;
CLIENT_NO CLIENT_NAME
BAL_DUE
----------------------------------------------------------C00001
Rahul
2100
C00002
Joyce
2000
C00003
Varsha
2300
C00004
Donald
2300
C00005
Jayesh
2400
C00006
Anoop
2300
C00007
Sunita
8000
C00008
Arjun
2200
8 rows selected.
PPPA
A
G
E
O
AG
GE
E 555111 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
SQL>
2
3
4
5
6
7
8
9
10
11
CREATE TRIGGER Audit_Trail
AFTER UPDATE OR DELETE ON Client_Master
FOR EACH ROW
DECLARE
/* The value in the oper variable will be inserted into the
operation field in the AuditClient table. */
Oper varchar2(8);
/* These variables will hold the previous values of Client
No,
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
Name and Bal Due. */
Client_No varchar2(6);
Client_Name varchar2(20);
Bal_Due number(10,2);
BEGIN
/* If the records are updated in Client Master table then
oper is set to 'Update'. */
IF updating THEN
Oper := 'Update';
END IF;
/* If the records are deleted in Client Master table then
oper is set to 'Delete'. */
IF Deleting THEN
Oper := 'Delete';
END IF;
/* Store Old Client No, Client Name and Bal Due into Client No,
Client Name and Bal Due. */
Client_No := :OLD.Client_No;
Client_Name := :OLD.Client_Name;
Bal_Due := :OLD.Bal_Due;
INSERT INTO Audit_Client
VALUES ( Client_No, Client_Name, Bal_Due,
Oper, User, sysdate );
END;
/
Trigger created.
PPPA
A
G
E
O
AG
GE
E 555222 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
SQL>
SELECT * FROM Audit_Client;
no rows selected
SQL>
2
3
UPDATE Client_Master
SET Bal_Due = 2000
WHERE Client_No = 'C00008';
1 row updated.
SQL>
2
SELECT Client_No, Client_Name, Bal_Due
FROM Client_Master;
CLIENT_NO CLIENT_NAME
BAL_DUE
----------------------------------------------------------C00001
Rahul
2100
C00002
Joyce
2000
C00003
Varsha
2300
C00004
Donald
2300
C00005
Jayesh
2400
C00006
Anoop
2300
C00007
Sunita
8000
C00008
Arjun
2000
8 rows selected.
SQL>
SELECT * FROM Audit_Client;
CLIENT_NO CLIENT_NAME BAL_DUE OPERATION USERID
ODATE
------------------- ------------------------- ----------------- -------------------- ------------- ---------------C00008
Arjun
2000
Update
SYSTEM 10-JAN08
PPPA
A
G
E
O
AG
GE
E 555333 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
SQL>
2
DELETE FROM Client_Master
WHERE Client_Name LIKE 'J%';
2 rows deleted.
SQL>
2
SELECT Client_No, Client_Name, Bal_Due
FROM Client_Master;
CLIENT_NO CLIENT_NAME
BAL_DUE
----------------------------------------------------------C00001
Rahul
2100
C00003
Varsha
2300
C00004
Donald
2300
C00006
Anoop
2300
C00007
Sunita
8000
C00008
Arjun
2000
6 rows selected.
SQL>
SELECT * FROM Audit_Client;
CLIENT_NO CLIENT_NAME BAL_DUE OPERATION USERID
ODATE
------------------- ------------------------- ----------------- -------------------- ------------- ---------------C00008
Arjun
2000
Update
SYSTEM 10-JAN08
C00002
Joyce
2000
Delete
SYSTEM
10-JAN-08
C00005
Jayesh
2400
Delete
SYSTEM 10-JAN08
PPPA
A
G
E
O
AG
GE
E 555444 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
Example 2:
Write a Database Trigger that allows changes to Employee Table
during the Business hours ( i.e., from 8 a.m. to 5 p.m. ) from Monday
to Saturday. There is no restriction on viewing data from the table.
SQL>
SELECT * FROM Employee;
EMP_CODE E_NAME
DEPT_NO
JOB
SALARY
-------------------- -------------------------------- ---------------- ---------------------------------E00001
Sasi Kumar
20
Analyst
12600
E00002
Akshaya Lakshmi
20
Testing
10500
E00003
Janaki Raman
25
Officer
11000
E00004
Prakash
15
Shepherd
12345.99
E00005
Mani Kandan
20
Project Head
9450
E00006
Hari Haran
30
HP Salesman
8000
E00007
Ranjith
30
Bike Man
7000
7 rows selected.
SQL>
2
3
4
5
6
7
8
9
10
11
CREATE OR REPLACE TRIGGER Time_Check
BEFORE INSERT OR UPDATE OR DELETE
ON Employee
BEGIN
IF ( to_number(to_char(sysdate,'hh24')) < 8 OR
to_number(to_char(sysdate,'hh24')) >= 17 OR
to_char(sysdate,'day') = 'SUN' ) THEN
RAISE_APPLICATION_ERROR(-20023,'Changes
to
12
Employee Table Allowed only during Business
Hours');
13
14
15
16
17
END IF;
END;
/
Trigger created.
PPPA
A
G
E
O
AG
GE
E 555555 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
SQL>
2
update employee set salary = 15000
where emp_code = 'E00001';
update employee set salary = 15000
*
ERROR at line 1:
ORA-20023:
Changes to Employee Table
Allowed only during Business Hours
ORA-06512:
ORA-04088:
at "SYSTEM.TIME_CHECK", line 7
error during execution of trigger 'SYSTEM.TIME_CHECK'
PPPA
A
G
E
O
AG
GE
E 555666 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
PROCEDURES
=============================================================
A Procedure is a logically grouped set of SQL and PL/SQL statements that
perform a specific task. A stored procedure is a named
PL/SQL code block that have been compiled and stored in
one of the Oracle engine’s system tables.
=============================================================
PPPA
A
G
E
O
AG
GE
E 555777 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
Syntax:CREATE OR REPLACE PROCEDURE [Schema.] ProcedureName
(Argument {IN, OUT, IN OUT} Data Type, … )
{ IS, AS }
Variable Declarations;
Constant Declarations;
BEGIN
PL/SQL SubProgram Body;
EXCEPTION
Exception PL/SQL Block;
END;
Keywords and Parameters:
REPLACE
Recreates the procedure if it already exists. This option is used to
change the definition of an existing procedure without dropping.
Schema
is the schema to contain the procedure. The Oracle engine takes the
default schema to be the current schema, if it is omitted.
ProcedureName
is the name of the procedure to be created.
Argument
is the name of an argument to the procedure. Parantheses can be
omitted if no arguments ar present.
IN
specifies that a value for the argument must be specified when
calling the procedure.
OUT
speciies that the procedure passes a value for this argument back to
its calling environment after execution.
IN OUT
specifies that a value for the argument must be specified when
calling the procedure and that the procedure passes a value for this
argument back to its calling environment after execution. By
default it takes IN.
DataType
is the data type of an argument. It supports any data type supported
by PL/SQL.
Example 1:
SQL>
2
3
4
CREATE OR REPLACE PROCEDURE Proc_Update
( VProductNo IN char, VSOrderNo IN char,
Quantity IN number ) IS
PPPA
A
G
E
O
AG
GE
E 555888 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/* Variable Declarations. */
Total_Qty_Ordered number(8);
Total_Qty_Disp number(8);
BEGIN
/* Updating the Qty On Hand in the Product Master
table */
UPDATE Product_Master
SET Qty_On_Hand = Qty_On_Hand - Quantity;
WHERE Product_No = VProductNo;
/* Checking in the Sales Order Details table the total
quantity ordered and the total quantity dispatched
for
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
a certain Sales Order and stuffing the values into
memory variables. */
SELECT SUM(Qty_Ordered), SUM(Qty_Disp)
INTO Total_Qty_Ordered, Total_Qty_Disp
FROM Sales_Order_Details
WHERE DetlOrder_No = VSOrderNo;
/* Comparing tha total quantity ordered with the total
quantity dispatched and updating the Order Status
in the Sales Order table. */
IF Total_Qty_Ordered = Total_Qty_Disp THEN
UPDATE Sales_Order
SET Order_Status = 'Fulfilled'
WHERE Order_No = VSOrder_No;
ELSIF Total_Qty_Disp = 0 THEN
UPDATE Sales_Order
SET Order_Status = 'BackOrder'
WHERE Order_No = VSOrder_No;
ELSE
UPDATE Sales_Order
SET Order_Status = 'In Process'
WHERE Order_No = VSOrder_No;
END IF;
END;
/
Procedure created.
PPPA
A
G
E
O
AG
GE
E 555999 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
SQL>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
DECLARE
/* Cursor C_Mast_Check retrieves all the records of
table Challan Header. */
CURSOR C_Mast_Check IS
SELECT Challan_No,Order_No FROM
Challan_Header;
/* Declaration of memory variables that will hold values. */
VProductNo varchar2(6);
VSOrderNo varchar2(6);
Quantity number(3);
VMastChallan varchar2(6);
VDetChallan varchar2(6);
BEGIN
/* Accepting values for Product No, Quantity Dispatched
and Challan No from the user and stuffing them in
memory variables. */
VProductNo := '&VProductNo';
Quantity := &Quantity;
VDetChallan := '&VDetChallan';
OPEN C_Mast_Check;
LOOP
FETCH C_Mast_Check INTO VMastChallan, VSOrderNo;
EXIT WHEN C_Mast_Check%NOTFOUND;
IF VDetChallan = VMastChallan THEN
INSERT INTO Challan_Details
VALUES(VDetChallan,VProductNo, Quantity );
/* Call Procedure Proc Update to update Sales
Order and Product Master tables. */
Proc_Update(VProductNo, VSOrderNo, Quantity);
EXIT;
END IF;
END LOOP;
IF C_Mast_Check%NOTFOUND THEN
DBMS_OUTPUT.PUT_LINE('The given
Challan No does not have a master record');
END IF;
PPPA
A
G
E
O
AG
GE
E 666000 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
50
51
52
53
54
55
CLOSE C_Mast_Check;
COMMIT;
END;
/
Enter value for vproductno: P00001
old 23: VProductNo := '&VProductNo';
new 23: VProductNo := 'P00001';
Enter value for quantity: 2
old 24: Quantity := &Quantity;
new 24: Quantity := 2;
Enter value for vdetchallan: 1
old 25: VDetChallan := '&VDetChallan';
new 25: VDetChallan := '1';
PL/SQL procedure successfully completed.
Example 2:
Write a Procedure that drops the objects specified by the user. This Procedure also
takes wildcards for object names. For example, if the user wants to
drop all object with name like ‘emp_%’, The following Procedure
uses both static and dynamic SQL.
SQL>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
CREATE OR REPLACE PROCEDURE Drop_Object_Proc
(Type_In IN varchar2, Name_In IN varchar2) IS
/* The static cursor retrieving the object. */
CURSOR Obj_Cur IS
SELECT Object_Name, Object_Type
FROM USER_OBJECTS
WHERE Object_Name LIKE UPPER(Name_In) AND
Object_Type LIKE UPPER(Type_In)
ORDER BY Object_Name;
/* Declaring a handle to the Dynamic SQL Cursor. */
Cursor_Handle integer;
BEGIN
/* For each matching object */
PPPA
A
G
E
O
AG
GE
E 666111 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
20
21
FOR Obj_Rec IN Obj_Cur
22
LOOP
23
24
/* Open new cursor and return cursor ID. */
25
26
Cursor_Handle := DBMS_SQL.OPEN_CURSOR;
27
28
/* Construct the SQL statement and parse it in version 7 mode. */
29
30
DBMS_SQL.PARSE(Cursor_Handle,'DROP ' ||
31 Obj_Rec.Object_Type || ' ' || Obj_Rec.Object_Name,DBMS_SQL.V7);
32
33
/* Close the cursor. */
34
35
DBMS_SQL.CLOSE_CURSOR(Cursor_Handle);
36
END LOOP;
37
38
END;
39
/
Procedure created.
SQL>
2
3
4
5
6
7
8
9
10
11
BEGIN
/* Call to the Procedure Drop Object Proc. The two
parameters the procedure takes is the type
of object and the name of the object. */
Drop_Object_Proc('SEQUENCE','MSG_SEQ');
DBMS_OUTPUT.PUT_LINE('Object Dropped
Successfully');
END;
/
Object Dropped Successfully
PL/SQL procedure successfully completed.
PPPA
A
G
E
O
AG
GE
E 666222 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
FUNCTIONS
=============================================================
A Function is a logically grouped set of SQL and PL/SQL statements that
perform a specific task. A stored function is a named
PL/SQL code block that have been compiled and stored in
one of the Oracle engine’s system tables.
=============================================================
PPPA
A
G
E
O
AG
GE
E 666333 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
Syntax:CREATE OR REPLACE FUNCTION [Schema.] FunctionName
(Argument IN Data Type, … )
RETURN Data Type { IS, AS }
Variable Declarations;
Constant Declarations;
BEGIN
PL/SQL SubProgram Body;
EXCEPTION
Exception PL/SQL Block;
END;
Keywords and Parameters:
REPLACE
Recreates the function if it already exists. This option is used to
change the definition of an existing function without dropping.
Schema
is the schema to contain the function. The Oracle engine takes the
default schema to be the current schema, if it is omitted.
FunctionName
is the name of the function to be created.
Argument
is the name of an argument to the function. Parantheses can be
omitted if no arguments are present.
IN
specifies that a value for the argument must be specified when
calling the function.
OUT
speciies that the function passes a value for this argument back to
its calling environment after execution.
IN OUT
specifies that a value for the argument must be specified when
calling the function and that the function passes a value for this
argument back to its calling environment after execution. By
default it takes IN.
DataType
is the data type of an argument. It supports any data type supported
by PL/SQL.
Example 1:
SQL>
2
3
4
CREATE FUNCTION F_ItemIDchk( VItemIDno IN number )
RETURN number IS
/* variable that holds data from the Item Master table. */
PPPA
A
G
E
O
AG
GE
E 666444 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
BEGIN
SELECT ItemID INTO DummyItem
FROM Item_Master
WHERE Item_ID = VItemIDno;
/* if the select statement retrieves data,
valexists is set to 1. */
RETURN 1;
EXCEPTION
/* if the select statement does not retrieve data,
valexists is set to 0. */
WHEN no_data_found THEN
RETURN 0;
END;
/
Function created.
SQL>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
DECLARE
/* Cursor scantable retrieves all the records
of all table itemtran */
CURSOR ScanTable IS
SELECT ItemID, Quantity, Description FROM
Item_Transaction;
/* Variables that hold data from the cursor scantable. */
VItemIDno Item_Transaction.ItemID%TYPE;
VDescrip Item_Transaction.Description%TYPE;
VQuantity Item_Transaction.Quantity%TYPE;
/* Variable that stores the value returned by
the F_ItemIDchk function i.e., 1 or 0 */
ValExists number(1);
BEGIN
OPEN ScanTable;
LOOP
PPPA
A
G
E
O
AG
GE
E 666555 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
FETCH ScanTable INTO VItemIDno,VQuantity,
VDescrip;
EXIT WHEN ScanTable%NOTFOUND;
/* Call function FItemIDchk to check if ItemID is
present in Item Master table. */
ValExists := F_ItemIDchk(VItemIDno);
/* If ItemID does not exists insert a record
in the Item Master table. */
IF ValExists = 0 THEN
INSERT INTO Item_Master(Item_ID,
Description, Bal_Stock)
VALUES(VItemIDno, VDescrip, VQuantity);
/* If the record is found then update quantity
in the Item Master table. */
ELSIF ValExists = 1 THEN
UPDATE Item_Master
SET Bal_Stock = Bal_Stock + VQuantity
WHERE ItemID = VItemIDno;
END IF;
END LOOP;
CLOSE ScanTable;
COMMIT;
END;
/
PL/SQL procedure successfully completed.
Example 2:
SQL>
2
3
4
5
6
7
8
9
10
11
12
CREATE OR REPLACE FUNCTION Gen_Pkey_Chk
(Table_Name IN varchar2, Col_Name IN varchar2,
Col_Value IN varchar2)
RETURN number AS
/* Declaring a handle to the Dynamic SQL cursor. */
Cursor_Handle integer;
/* Variable that holds the return value from the EXECUTE. */
Execute_Feedback integer;
PPPA
A
G
E
O
AG
GE
E 666666 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
13
14
15
16
17
18
19
20
21
BEGIN
/* Open new cursor and return cursor ID. */
Cursor_Handle := DBMS_SQL.OPEN_CURSOR;
/* Parse the query with the columns in the SELECT list. */
DBMS_SQL.PARSE(Cursor_Handle,'SELECT' ||
Col_Name
|| 'FROM' ||Table_Name || 'WHERE' || Col_Name || ' = " '
|| Col_Value || ' " ' , DBMS_SQL.V7);
22
23
24
25
26
/* Execute the SQL statement. */
Execute_Feedback :=
DBMS_SQL.EXECUTE(Cursor_Handle);
27
28
29
30
31
/* Returning values 0 or 1 depending upon whether the select
returned a row or not and closing the cursor. */
IF DBMS_SQL.FETCH_ROWS(Cursor_Handle) = 0
THEN
32
33
34
35
36
37
38
39
40
41
42
DBMS_SQL.CLOSE_CURSOR(Cursor_Handle);
RETURN 0;
ELSE
DBMS_SQL.CLOSE_CURSOR(Cursor_Handle);
RETURN 1;
END IF;
END;
/
Function created.
SQL>
2
3
4
DECLARE
/* Declaring a variable that will hold the return value of
the function.
*/
5
6
7
8
9
10
11
12
Rows_Found number;
BEGIN
/* Calling the function Gen_Pkey_chk that takes the table name
and column name/s as the IN parameter and returns a number. */
Rows_Found := Gen_Pkey_Chk('&Table_Name',
PPPA
A
G
E
O
AG
GE
E 666777 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
13
14
15
16
17
18
19
20
21
22
23
24
25
'&ColumnName', '&ColumnValue');
/* Displaying message to the user. */
IF Rows_Found = 0 THEN
DBMS_OUTPUT.PUT_LINE('The Column value is Unique');
ELSE
DBMS_OUTPUT.PUT_LINE('The Column value is not Unique');
END IF;
END;
/
Enter value for table_name: sales_order_details
Enter value for columnname: detorder_no
Enter value for columnvalue: product_no
old 12: Rows_Found := Gen_Pkey_Chk('&Table_Name', '&ColumnName',
'&ColumnValue');
new 12: Rows_Found := Gen_Pkey_Chk('sales_order_details', 'detorder_no',
'product_no');
The column value is unique
PPPA
A
G
E
O
AG
GE
E 666888 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
PACKAGES
=============================================================
A package is an Oracle object, which holds other objects within it. Objects commonly
held within a package are Procedures, Functions, Variables,
Constants, Cursors and Exceptions. The tool used to create a
package is SQL*Plus. It is a way of creating generic, encapsulated,
re-usable code.
=============================================================
PPPA
A
G
E
O
AG
GE
E 666999 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
Syntax:CREATE PACKAGE PackageName AS
{
.....
.....
.....
}
END PackageName;
Example 1:
SQL>
2
3
4
5
6
7
8
9
CREATE OR REPLACE PACKAGE PackageName AS
FUNCTION F_ItemIDChk( VItemIDno IN number )
RETURN number;
PROCEDURE Proc_Update( VItemIDno IN number,
Quantity IN number);
PROCEDURE Proc_Insert( VItemIDno IN number,
Quantity IN number, Descrip
varchar2);
END Check_Data;
/
Package created.
SQL>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
CREATE OR REPLACE PACKAGE BODY Check_Data IS
FUNCTION F_ItemIDchk (VItemIDno IN number)
RETURN number IS
DummyItem number(4);
BEGIN
SELECT ItemID INTO DummyItem
FROM Item_Master
WHERE ItemID = VItemIDno;
RETURN 1;
EXCEPTION
WHEN no_data_found THEN
RETURN 0;
END;
PROCEDURE Proc_Insert (VItemIDno IN number,
Quantity IN number, Descrip IN varchar2) IS
PPPA
A
G
E
O
AG
GE
E 777000 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
BEGIN
INSERT INTO Item_Master( ItemID, Bal_Stock,
Description)
VALUES(VItemIDno, Quantity, Descrip);
END;
PROCEDURE Proc_Update(VItemIDno IN number,
Quantity IN number) IS
BEGIN
UPDATE Item_Master SET
Item_Master.Bal_Stock = Quantity
WHERE ItemID = VItemIDno;
END;
END Check_Data;
/
Package Body created.
Example 2:
SQL>
2
3
4
5
CREATE OR REPLACE PACKAGE Employee_Incentives IS
PROCEDURE Give_Emp_Raise(Dept_No IN number);
PROCEDURE Give_Emp_Raise(Dept_Name IN
varchar2);
END;
/
Package created.
SQL>
2
3
4
5
6
7
8
9
10
11
12
13
CREATE OR REPLACE PACKAGE BODY
Employee_Incentives IS
PROCEDURE Give_Emp_Raise(Dept_No IN number) IS
CURSOR C_Emp(C_Dept_No number) IS
SELECT Emp_Code, Salary FROM Employee
WHERE Dept_No = C_Dept_No;
Str_Emp_Code Employee.Emp_Code%TYPE;
Num_Salary Employee.Salary%TYPE;
BEGIN
OPEN C_Emp(Dept_No);
IF C_Emp%ISOPEN THEN
LOOP
FETCH C_Emp INTO Str_Emp_Code, Num_Salary;
PPPA
A
G
E
O
AG
GE
E 777111 O
OFFF 777222
SSSQ
Q
L
&
L
Q
L
C
m
m
QL
L&
& PPPL
L///SSSQ
QL
LC
Cooom
mm
maaannndddsss
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
EXIT WHEN C_Emp%NOTFOUND;
UPDATE Employee
SET Salary = Num_Salary + (Num_Salary * 0.05)
WHERE Emp_code = Str_Emp_Code;
INSERT INTO Emp_Raise VALUES (Str_Emp_Code,
sysdate,Num_Salary * 0.05);
END LOOP;
COMMIT;
CLOSE C_Emp;
ELSE
DBMS_OUTPUT.PUT_LINE('Unable to open Cursor');
END IF;
END;
PROCEDURE Give_Emp_Raise(Dept_Name IN varchar2) IS
CURSOR C_Emp(C_Dept_Name varchar2) IS
SELECT Emp_Code, Salary FROM Employee, Dept
WHERE Employee.Dept_No = Dept.Dept_No AND
DName = C_Dept_Name;
Str_Emp_Code Employee.Emp_Code%TYPE;
Num_Salary Employee.Salary%TYPE;
BEGIN
OPEN C_Emp(Dept_Name);
IF C_Emp%ISOPEN THEN
LOOP
FETCH C_Emp INTO Str_Emp_Code, Num_Salary;
EXIT WHEN C_Emp%NOTFOUND;
UPDATE Employee
SET Salary = Num_Salary + (Num_Salary * 0.05)
Where Emp_Code = Str_Emp_code;
INSERT INTO Emp_Raise VALUES( Str_Emp_Code,
sysdate, Num_Salary * 0.05);
END LOOP;
COMMIT;
CLOSE C_Emp;
ELSE
DBMS_OUTPUT.PUT_LINE('Unable to open Cursor');
END IF;
END;
END Employee_Incentives;
/
Package Body created.
PPPA
A
G
E
O
AG
GE
E 777222 O
OFFF 777222
© Copyright 2026 Paperzz