Oracle Notes
Oracle Notes
SQL PL/SQL
->
'c' - lang.
DB FUNDAMENTALS :
-----------------
-> Where we can store the data permanently that location name is
called as DATABASE
BANK DB ( SERVER )
.
.
.
.
100000
-> we can write queries by using SELECT, INSERT, UPDATE, DELETE, CREATE,
etc., commands
-> Where can store the data permanently for future reference
W/L - 20 ->
->
-> In relational datbases the relations are mainting by usign PRIMARY KEY
& FOREIGN KEY Constraints
History of Databases :
----------------------
Dis. Adv. :
-----------
II. DATABASE :
--------------
dis. adv. :
-----------
-> Normal databases are not supported multiple users and multiple
platforms
-> In this Databases Data will be stored in ROWS and COLUMNS format
-> Data Retrieval and Manipulations are very fast( 10 -9 nano sec.,) we
can fetch the data, bcz.,
relational dbs are supports INDEX mechanism
-> All Relational Databsaes are supports Multiple Users and Multiple
Platforms
ORACLE VERSIONS:
----------------
i. OLTP
ii. OLAP
1981 10
1982 15
1981 1982
10 15
oracle :
---------
o/p: 5
sql server:
-----------
select sqrt(25)
o/p: 5
i. Express Edition
ii. Enterprize Edition
i. Express Edition :
--------------------
username : system
password : server
ex:
** once user created, you should be grant the permissions to connect user
:
*************************************************************************
***
ex:-
syn:-
ex:-
USERNAME
------------------------------
ORA8PM
SYS
SYSTEM
ANONYMOUS
APEX_PUBLIC_USER
FLOWS_FILES
APEX_040000
OUTLN
DIP
ORACLE_OCM
XS$NULL
USERNAME
------------------------------
MDSYS
CTXSYS
DBSNMP
XDB
APPQOSSYS
HR
17 rows selected.
syn :-
Drop User <user_name>;
ex:-
note: ** From Oracle 12c onwards before username should be place 'C##' is
required
username: ora8pm
password: tiger
sql>
cl scr:
-------
ORACLE DATATYPES :
------------------
i. Simple Datatypes
i. Simple Datatypes :
---------------------
ex :-
EMPID NUMBER(4);
note: in NUMBER datatype each and every time Scale part(2) is sub-
traction from Precision part(5) i.e., ( 5 - 2 = 3)
SALARY NUMBER(7,2);
(5,2);
ii. CHAR(size) :
----------------
ex:-
Employ_Name Char(20);
'RAMA------'
'KRISHNA---'
PanCardNo char(10);
iii. VARCHAR2(SIZE) :
---------------------
Employ_name varchar2(10);
iv. DATE(size) :
----------------
ex:-
-> in above 2nd exmaple oracle taken as 2083 bcz., by defualt ORACLE
taking CURRENT CENTURY
08/23/23
LONG :
------
ex:-
Remarks LONG;
emp_resume LONG;
-> These datatypes are supports Images, Audio Files, & Video files
ex:-
-> These datatypes are accepts images, audio files and video files
Emp_Photo CLOB;
Emp_Video BLOB;
Emp_doc CLOB;
BFILE :
-------
ex:-
i. SELECT
i. Create :
-----------
TABLE :
-------
Syntax :
--------
ex:-
-- create a ordered table with order id, order date, item name,
quantity, date of booking, date of delivery, customer id & remarks
DESC <table_name> :
-------------------
a. add :
--------
ex:-
Table altered.
b. modify :
-----------
Table altered.
Table altered.
ex:-
Table altered.
ex:-
-- to drop a single column
syn:-
ex:-
IV. TRUNCATE :
--------------
-> This command used to DELETE ALL RECORDS from the table Permanently
ex:-
V. DROP( TABLE ) :
-------------------
-> This command is used to delete all records and structure from the
DB Permanently
-> Rollback not supported, but we can restore the table by using
FLASHBACK queries
syn:-
ex:-
i. insert :
-----------
syn:-
ex:-
1 row created.
SQL> Insert into employee_db values( '102', 'Scott', 6000, 20, 'Clerk'
);
Insert into employee_db values( '102', 'Scott', 6000, 20, 'Clerk' )
*
ERROR at line 1:
ORA-00947: not enough values
ex:-
Inseting NULLs:
---------------
-> While inserting data, if we don't have any column values instead of
that column values to use NULLs
i. EXPLICIT NULL :
==================
EX:-
SQL> Insert Into employee_db values( '103', 'Smith', NULL, 30, NULL, NULL
);
1 row created.
ex:-
-- If we don't have BASIC_SALARY, JOB & REMARKS
I. Single &
I. Single & :
-------------
ex:-
1 row created.
SQL> /
Enter value for empid: 106
Enter value for ename: 'Blake'
Enter value for basic_salary: 6500
Enter value for deptno: 30
Enter value for job: 'Analyst'
Enter value for remarks: 'No'
old 1: Insert Into Employee_db values( &Empid, &Ename, &basic_salary,
&deptno, &job, &remarks )
new 1: Insert Into Employee_db values( 106, 'Blake', 6500, 30,
'Analyst', 'No' )
1 row created.
SQL BUFFER :
------------
-> SQL buffer is a Temporary Buffer and it holds latest executed query
-> Inside the table if any column values is fixed / common then to use
this &&
ex:-
1 row created.
1 row created.
SQL> /
Enter value for empid: '103'
Enter value for ename: 'james'
Enter value for deptno: 30
1 row created.
SQL> /
Enter value for empid: '104'
Enter value for ename: 'allen'
Enter value for deptno: 20
1 row created.
SQL> /
Enter value for empid: '105'
Enter value for ename: 'blake'
Enter value for deptno: 30
1 row created.
-> This command is used to delete all records or specified records from
table temporarily
syn:-
ex:-
syn:-
Table altered.
5 rows updated.
ex2:-
-- waq to set employee name as ANAND, Salary as 8500 for empid 1003
1 row updated.
ex2:-
-- waq to delete all Employee Salaries
5 rows updated.
NOTE: to delete COLUMN values then use UPDATE command by using NULL
1 row updated.
1 row updated.
SQL> /
Enter value for empid: 104
old 1: Update employee_db set basic_salary=&basic_salary where
empid=&Empid
new 1: Update employee_db set basic_salary=9000 where empid=104
1 row updated.
ex3:-
step 1:
-------
Table altered.
5 rows updated.
i. SELECT
i. SELECT :
-----------
syn:-
Select * / column_list from <table_name> [WHERE <condition>/
GROUP BY Clause/
HAVING Clause /
ORDER BY clause ];
ex:-
EMPI MAIL_ID
---- --------------------
101 [email protected]
102 [email protected]
103 [email protected]
104 [email protected]
105 [email protected]
** Oracle provided some demo tables for practice purpose those tables
are...
CRUID operations
ORACLE Operators :
------------------
i. Arithmetic Operators : +, -, * , /
vi. Special Operators : IN,NOT IN, BETWEEN, NOT BETWEEN, LIKE, NOT LIKE,
IS NULL, IS NOT NULL
Priority of Operators :
-----------------------
-- waq to display whose employee nos. are matched with 7788, 7369, 7839
& 7902
Special Operators :
-------------------
IN :
-----
-- waq to display whose employee nos. are matched with 7788, 7369, 7839
& 7902
SQL> select * from emp where empno IN ( 7788, 7839, 7369, 7902 );
ex:-
6 rows selected.
NOT IN :
--------
-> this operator used to compares other than given list of values
ex:-
-- waq to display whose names not matched with SMITH, ALLEN & FORD
SQL> SELECT * FROM EMP WHERE ENAME NOT IN ( 'SMITH', 'ALLEN', 'FORD');
11 rows selected.
BETWEEN :
---------
-> this operator compares the data based on given RANGE
ex:-
SQL> select * from emp where sal between 1000 and 4000;
11 rows selected.
NOT BETWEEN :
-------------
ex:-
SQL> select * from emp where hiredate not between '01-jan-81' and '31-
dec-81';
LIKE :
-------
ex:-
8 rows selected.
NOT LIKE:
---------
SQL> select ENAME from emp where ENAME NOT LIKE '%S%';
ENAME
----------
ALLEN
WARD
MARTIN
BLAKE
CLARK
KING
TURNER
FORD
MILLER
9 rows selected.
10 rows selected.
IS NULL :
--------
ex:-
10 rows selected.
IS NOT NULL :
-------------
Examples :
----------
14 rows selected.
ENAME
----------
SMITH
TRUTH TABLES :
--------------
AND
----
I1 I2 O/P
T T T
T F F
F T F
F F F
OR
----
I1 I2 O/P
T T T
T F T
F T T
F F F
NOT
---
I1 O/P
T F
F T
no rows selected
8 rows selected.
i. Pre-defined Function :-
I. Pre-defined Function :
*************************
-> These functions are executed on each and every column value
a. Number Functions
b. Character Functions
c. Date Functions
a. Number Functions :
---------------------
ABS() :
-------
ex:-
ABS(-100)
---------
100
100
100
100
100
100
100
100
100
100
100
100
100
100
14 rows selected.
ABS(-100)
---------
100
100
100
100
ABS(-100)
---------
100
NOTE: above executions, DUAL table contains only one record so, ABS
function called only 1 time.
ii. POWER() :
-------------
POWER(2,3)
----------
8
iii. SQRT() :
-------------
SQRT(25)
--------
5
SQRT(625)
---------
25
SQRT(ABS(-625))
---------------
25
MOD() :
--------
ex:-
MOD(10,2)
---------
0
SQL>
SQL> select mod(13,2) from dual;
MOD(13,2)
---------
1
13 rows selected.
SIGN() :
--------
0 then returns 0
ex:-
SIGN(1000)
----------
1
SIGN(-1000)
-----------
-1
SIGN(0)
-------
0
SIN() :
-------
COS() :
-------
TAN() :
-------
ROUND() :
---------
ROUND(16.8)
-----------
17
ROUND(16.3)
-----------
16
ROUND(16.79,1)
--------------
16.8
ROUND(16.5,1)
-------------
16.5
ROUND(16.748,2)
---------------
16.75
CEIL :
------
-> this function rounded upper bound value
CEIL(16.7)
----------
17
TRUNC() :
---------
ex:-
TRUNC(16.8)
-----------
16
TRUNC(16.76,1)
--------------
16.7
TRUNC(16.768,2)
---------------
16.76
FLOOR :
-------
FLOOR(16.7)
-----------
16
EMPNO ROUND(SAL/30)
------ -------------
7369 27
7499 53
7521 42
7566 99
7654 42
7698 95
7782 82
7788 100
7839 167
7844 50
7876 37
7900 32
7902 100
7934 43
14 rows selected.
SYSDATE
---------
14-AUG-23
EMPNO SYSDATE-HIREDATE
------ ----------------
7369 15581
7499 15516
7521 15514
7566 15475
7654 15296
7698 15446
7782 15407
7788 14859
7839 15246
7844 15316
7876 14825
7900 15230
7902 15230
7934 15179
14 rows selected.
EMPNO (SYSDATE-HIREDATE)/365
------ ----------------------
7369 42.687
7499 42.509
7521 42.504
7566 42.397
7654 41.906
7698 42.317
7782 42.211
7788 40.709
7839 41.77
7844 41.961
7876 40.616
7900 41.726
7902 41.726
7934 41.586
14 rows selected.
EMPNO ROUND((SYSDATE-HIREDATE)/365)
------ -----------------------------
7369 43
7499 43
7521 43
7566 42
7654 42
7698 42
7782 42
7788 41
7839 42
7844 42
7876 41
7900 42
7902 42
7934 42
14 rows selected.
lower() :
---------
LOWER('NA
---------
naresh it
upper() :
---------
UPPER('NA
---------
NARESH IT
INITCAP() :
-----------
INITCAP('NARESHIT,HYD
---------------------
Naresh It, Hyderabad.
LENGTH() :
----------
LENGTH('NARESHIT')
------------------
9
ENAME
----------
MARTIN
TURNER
MILLER
14 rows selected.
LPAD() :
--------
LPAD('NARE
----------
NARESH
LPAD('NARE
----------
****NARESH
RPAD() :
--------
RPAD('NARE
----------
NARESH****
** to display bothsides
LPAD('NARESH
------------
***NARESH IT
RPAD(LPAD('NARE
---------------
***NARESH IT***
CONCAT() :
----------
ex:-
CONCAT('
--------
NARESHIT
Nested functions :
------------------
CONCAT(CONCAT('N
----------------
NARESHITAmeerpet
CONCAT(CONCAT('NARE
-------------------
NARESH IT,Ameerpet.
ex:-
'MR.'||'SIVA'||'RAMA'||'K
-------------------------
Mr.Siva Rama Krishna Raju
ii. Mr. Smith is working as a Clerk and getting Annual Salary Rs.60000
'MR.'||ENAME||'ISWORKINGASA'||JOB
---------------------------------------
Mr.SMITH is working as a CLERK
Mr.ALLEN is working as a SALESMAN
Mr.WARD is working as a SALESMAN
Mr.JONES is working as a MANAGER
Mr.MARTIN is working as a SALESMAN
Mr.BLAKE is working as a MANAGER
Mr.CLARK is working as a MANAGER
Mr.SCOTT is working as a ANALYST
Mr.KING is working as a PRESIDENT
Mr.TURNER is working as a SALESMAN
Mr.ADAMS is working as a CLERK
Mr.JAMES is working as a CLERK
Mr.FORD is working as a ANALYST
Mr.MILLER is working as a CLERK
14 rows selected.
'MR.'||ENAME||'ISWORKINGASA'||JOB||'ANDGETTINGANNUALSALARYRS.'||(SAL*12)
-------------------------------------------------------------------------
---------------------------
Mr.SMITH is working as a CLERK and getting Annual Salary Rs.9600
Mr.ALLEN is working as a SALESMAN and getting Annual Salary Rs.19200
Mr.WARD is working as a SALESMAN and getting Annual Salary Rs.15000
Mr.JONES is working as a MANAGER and getting Annual Salary Rs.35700
Mr.MARTIN is working as a SALESMAN and getting Annual Salary Rs.15000
Mr.BLAKE is working as a MANAGER and getting Annual Salary Rs.34200
Mr.CLARK is working as a MANAGER and getting Annual Salary Rs.29400
Mr.SCOTT is working as a ANALYST and getting Annual Salary Rs.36000
Mr.KING is working as a PRESIDENT and getting Annual Salary Rs.60000
Mr.TURNER is working as a SALESMAN and getting Annual Salary Rs.18000
Mr.ADAMS is working as a CLERK and getting Annual Salary Rs.13200
Mr.JAMES is working as a CLERK and getting Annual Salary Rs.11400
Mr.FORD is working as a ANALYST and getting Annual Salary Rs.36000
Mr.MILLER is working as a CLERK and getting Annual Salary Rs.15600
14 rows selected.
LTRIM() :
---------
LTRI
----
RAMA
Rtrim() :
---------
RTR
---
RAM
TRIM() :
--------
TRI
---
RAM
no rows selected
REPLACE() :
-----------
REPLACE('A
----------
ICICI BANK
REPLACE('JACKA
--------------
BLACK AND BLUE
TRANSLATE() :
-------------
TRANSLATE
---------
resident
SUBSTRING() :
-------------
ex:-
SUBSTR(
-------
KRISHNA
ex2:-
SUBS
----
KRIS
ex3:-
SUBSTR(
-------
KRISHNA
-7 -> substring position is counting from Right -> left, but output
displays Left -> Right
ex4:-
INSTR() :
---------
ex:-
INSTR('ORACLECORPORATION','OR',3,2)
-----------------------------------
12
note: postion is counting from 1st char. onwards from left -> right(
fixed )
ex2:-
INSTR('ORACLECORPORATION','OR',3,3)
-----------------------------------
0
note: postion is counting from 1st char. onwards from left -> right(
fixed )
ex3:-
INSTR('ORACLECORPORATION','OR')
-----------------------------------
1
note: postion is counting from 1st char. onwards from left -> right(
fixed )
ex4:-
INSTR('ORACLECORPORATION','OR',3,2)
-----------------------------------
12
-1 -> Searching starting from 1st char. onwards from RIGHT -> LEFT
note: postion is counting from 1st char. onwards from left -> right(
fixed )
-- waq to display which employee names 'A' char. contains mininum 2 times
ENAME INSTR(ENAME,'A',1,2)
---------- --------------------
SMITH 0
ALLEN 0
WARD 0
JONES 0
MARTIN 0
BLAKE 0
CLARK 0
SCOTT 0
KING 0
TURNER 0
ADAMS 3
JAMES 0
FORD 0
MILLER 0
14 rows selected.
ENAME INSTR(ENAME,'A',1,2)
---------- --------------------
ADAMS 3
ex:-
1,anand,'ameerpet hyderabad'
2,raj,'panjagutta hyderabad'
.
.
table creation:
---------------
SUBSTR('
--------
ameerpet
SUBSTR('PA
----------
panjagutta
SUBSTR('A
---------
hyderabad
email-id:
---------
[email protected]
[email protected]
[email protected]
select
substr('[email protected]',1,instr('[email protected]','@',1,1)-1)
from dual;
-----------------------------
----
5-1=4
1 - Substring position displays from 1st Char onwords up to 4 chars
SUBS
----
king
select substr('[email protected]',instr('[email protected]','@',-
1,1)+1) from dual;
-------------------------------
---
15+1=16
16 - Substring position displays from 16th char onwords
SUBSTR('KING@
--------------
rediffmail.com
LTRIM('RAMESHSACH
-----------------
SACHIN TENDULKAR
RTRIM(LT
--------
SACHIN
TRIM(R
------
SACHIN
ex:-
SYSDATE :
---------
ex:-
SYSDATE
---------
18-AUG-23
ii. ADD_MONTHS() :
------------------
ADD_MONTH
---------
18-OCT-23
ADD_MONTH
---------
18-JUN-23
iii. MONTHS_BETWEEN() :
-----------------------
-> It returns months between two given dates
ex:-
MONTHS_BETWEEN(SYSDATE,'01-JAN-2023')
-------------------------------------
7.5757
iv. NEXT_DAY() :
----------------
NEXT_DAY(
---------
21-AUG-23
NEXT_DAY(
---------
21-AUG-23
v. LAST_DAY() :
---------------
LAST_DAY(
---------
31-AUG-23
EMPNO ROUND((SYSDATE-HIREDATE)/365)
------ -----------------------------
7369 43
7499 43
7521 43
7566 42
7654 42
7698 42
7782 42
7788 41
7839 42
7844 42
7876 41
7900 42
7902 42
7934 42
14 rows selected.
EMPNO ROUND(MONTHS_BETWEEN(SYSDATE,HIREDATE)/12)
------ ------------------------------------------
7369 43
7499 42
7521 42
7566 42
7654 42
7698 42
7782 42
7788 41
7839 42
7844 42
7876 41
7900 42
7902 42
7934 42
14 rows selected.
LAST_DAY(
---------
01-SEP-23
ADD_MONTH
---------
01-AUG-23
2nd Saturday :
--------------
NEXT_DAY(
---------
12-AUG-23
4th Saturday :
--------------
NEXT_DAY(
---------
26-AUG-23
-> These functions can compare multiple values and return single value
output
ex:-
MIN() :
-------
-> this function returns min value from given list of values
MIN(SAL)
--------
800
MAX() :
-------
MAX(SAL)
--------
5000
SUM() :
-------
SUM(SAL)
--------
29025
AVG() :
-------
COUNT() :
---------
ex:-
COUNT(EMPNO)
------------
14
COUNT(COMM)
-----------
4
COUNT(*)
--------
14
COUNT(1)
--------
14
COUNT(2)
--------
14
SUM(2)
------
28
other examples :
----------------
MIN(HIRED
---------
17-DEC-80
MAX(HIRED
---------
12-JAN-83
MAX(ENAME)
----------
WARD
MIN(ENAME)
----------
ADAMS
ERROR at line 1:
ORA-01722: invalid number
*
ERROR at line 1:
ORA-01722: invalid number
ex:-
TABLENAME: table_a
ColumnName: column_1
12
9
0
null
null
1
8
0
null
9
null
7
o/p: COUNT(COLUMN_1)
---------------
8
o/p: COUNT(*)
--------
12
o/p: COUNT(DISTINCT(COLUMN_1))
-------------------------
6
ERROT at line 1:
ORA-00936 missing expression
ans:- WARD
ex:- ADAMS
TABLENAME: table_a
ColumnName: column_1
12
9
0
null
null
1
8
0
null
9
null
7
o/p: 8
o/p: 14
o/p: 6
o/p:
ERROR at line 1:
ORA-00936: missing expression
i. TO_CHAR()
ii. TO_NUMBER()
iii. TO_DATE()
i. TO_CHAR() :
----------------
-> This function converts any DATE / NUMBER values into CHARACTER
format temporarily
or
-> This function converts ORACLE PRE-DEFINED date format into USER
DEFINED Date format temporarily
examples :
----------
ex:-
SYSDATE
---------
21-AUG-23
DATE FORMATS :
--------------
T
-
2
TO
--
21
TO_
---
233
TO_CHAR(SYSD
------------
mon
TO_CHAR(SYSDATE,'DAY')
------------------------------------
monday
T
-
3
TO
--
34
TO
--
08
TO_CHAR(SYSD
------------
aug
TO_CHAR(SYSDATE,'MONTH')
------------------------------------
august
T
-
3
TO
--
23
TO_
---
023
TO_C
----
2023
TO_CHAR(SYSDATE,'YEAR')
------------------------------------------
twenty twenty-three
TO
--
21
T
-
3
TO_C
----
21st
'ddsp' -> day of the month in spelling format
TO_CHAR(SYSD
------------
twenty-one
TO_CHAR
-------
2460178
note: above 'j' returns no.of days from oracle starting date to till date
examples:-
i. 21/08/23
TO_CHAR(
--------
21/08/23
TO_CHAR(SYSDATE,'DDTHMON
------------------------
21st aug, 2023.
EMPNO TO_CHAR(HI
------ ----------
7369 17/12/1980
7499 20/02/1981
7521 22/02/1981
7566 02/04/1981
7654 28/09/1981
7698 01/05/1981
7782 09/06/1981
7788 09/12/1982
7839 17/11/1981
7844 08/09/1981
7876 12/01/1983
7900 03/12/1981
7902 03/12/1981
7934 23/01/1982
14 rows selected.
EMPNO TO_CHAR(HI
------ ----------
7369 12/17/1980
7499 02/20/1981
7521 02/22/1981
7566 04/02/1981
7654 09/28/1981
7698 05/01/1981
7782 06/09/1981
7788 12/09/1982
7839 11/17/1981
7844 09/08/1981
7876 01/12/1983
7900 12/03/1981
7902 12/03/1981
7934 01/23/1982
14 rows selected.
10 rows selected.
-- waq to display who joined last week from the current year
SQL> select * from emp where to_char(hiredate,'ww') =
to_char(sysdate,'ww') -1
and
to_char(hiredate,'yyyy' ) =
to_char(sysdate,'yyyy');
-- waq to display who are joined in current week of the current year
-- waq to display each employee total sum of salary upto last month.
5,000.00
6,000.00
.
.
.
4,500.00
EMPNO TO_CHAR(SA
---------- ----------
7369 800.00
7499 1,600.00
7521 1,250.00
7566 2,975.00
7654 1,250.00
7698 2,850.00
7782 2,450.00
7788 3,000.00
7839 5,000.00
7844 1,500.00
7876 1,100.00
7900 950.00
7902 3,000.00
7934 1,300.00
14 rows selected.
NUMBER FORMATS :
----------------
EMPNO TO_CHAR(SAL,'L99,999
---------- --------------------
7369 $800.00
7499 $1,600.00
7521 $1,250.00
7566 $2,975.00
7654 $1,250.00
7698 $2,850.00
7782 $2,450.00
EMPNO TO_CHAR(SAL,'C99,
---------- -----------------
7369 USD800.00
7499 USD1,600.00
7521 USD1,250.00
7566 USD2,975.00
7654 USD1,250.00
7698 USD2,850.00
7782 USD2,450.00
EMPNO TO_CHAR(SA
---------- ----------
7369 +800.00
7499 +1,600.00
7521 +1,250.00
7566 +2,975.00
7654 +1,250.00
** To display currency with Indian Rupees
Session altered.
EMPNO TO_CHAR(SAL,'L99,999
---------- --------------------
7369 Rs800.00
7499 Rs1,600.00
7521 Rs1,250.00
7566 Rs2,975.00
7654 Rs1,250.00
7698 Rs2,850.00
7782 Rs2,450.00
7788 Rs3,000.00
7839 Rs5,000.00
7844 Rs1,500.00
7876 Rs1,100.00
7900 Rs950.00
7902 Rs3,000.00
7934 Rs1,300.00
14 rows selected.
EMPNO TO_CHAR(SAL,'C99,
---------- -----------------
7369 INR800.00
7499 INR1,600.00
7521 INR1,250.00
7566 INR2,975.00
7654 INR1,250.00
7698 INR2,850.00
7782 INR2,450.00
7788 INR3,000.00
7839 INR5,000.00
7844 INR1,500.00
7876 INR1,100.00
7900 INR950.00
7902 INR3,000.00
7934 INR1,300.00
14 rows selected.
EMPNO TO_CHAR(SA
---------- ----------
7369 +800.00
7499 +1,600.00
7521 +1,250.00
7566 +2,975.00
7654 +1,250.00
7698 +2,850.00
7782 +2,450.00
7788 +3,000.00
7839 +5,000.00
7844 +1,500.00
7876 +1,100.00
7900 +950.00
7902 +3,000.00
7934 +1,300.00
14 rows selected.
Session altered.
EMPNO TO_CHAR(SAL,'L99,999
---------- --------------------
7369 Ñ800.00
7499 Ñ1,600.00
7521 Ñ1,250.00
7566 Ñ2,975.00
7654 Ñ1,250.00
7698 Ñ2,850.00
7782 Ñ2,450.00
7788 Ñ3,000.00
7839 Ñ5,000.00
7844 Ñ1,500.00
7876 Ñ1,100.00
7900 Ñ950.00
7902 Ñ3,000.00
7934 Ñ1,300.00
14 rows selected.
EMPNO TO_CHAR(SAL,'C99,
---------- -----------------
7369 JPY800.00
7499 JPY1,600.00
7521 JPY1,250.00
7566 JPY2,975.00
7654 JPY1,250.00
7698 JPY2,850.00
7782 JPY2,450.00
7788 JPY3,000.00
7839 JPY5,000.00
7844 JPY1,500.00
7876 JPY1,100.00
7900 JPY950.00
7902 JPY3,000.00
7934 JPY1,300.00
14 rows selected.
SYSDATE
--------
23-08-22
Session altered.
SYSDATE
--------
22-08-23
II. TO_DATE() :
---------------
-> This function converts any USER DEFINED DATE format into ORACLE
DEFAULT DATE Format
ex:-
TO_DATE('
---------
22-AUG-23
ex2:-
TO_DATE('
---------
22-AUG-23
note:-
III. TO_NUMBER() :
------------------
-> this function convert CHAR. NUMBER values into NUMBER format
temporarily
ex:-
-- to find sum of two given numbers
'1,234.57' , '789.78'
ex:-
TO_NUMBER('1,234.57','9,999.99')+TO_NUMBER('789.89','999.99')
-------------------------------------------------------------
2024.46
ex:-
GREATEST() :
------------
GREATEST(10,20,30,40)
---------------------
40
ex:-
LEAST() :
---------
LEAS
----
abcd
UID :
------
UID
----------
48
USER :
------
USER
------------------------------
ORA8PM
DISTINCT() :
------------
JOB
---------
CLERK
SALESMAN
PRESIDENT
MANAGER
ANALYST
DEPTNO
----------
30
20
10
NVL() :
-------
Syn:-
NVL(expr1,expr2) :
******************
ex:-
NVL(NULL,100) NVL(500,1000)
------------- -------------
100 500
14 rows selected.
SQL> SELECT EMPNO, SAL, NVL( COMM,0), SAL + NVL(COMM,0) FROM EMP;
14 rows selected.
SOUNDEX() :
-----------
-> this function used to compares the data based on given pronounsation
ex:-
no rows selected
no rows selected
rule 1:
-------
-- In SELECT statement selected columns all are ordinary columns then,
it executs successfully.
rule 2:
-------
WHERE Clause :
--------------
Syntax:-
--------
GROUP BY Clause :
-----------------
-> Whenever an ordinary column retrieved along with group function then
all ordinary columns must be
placed after GROUP BY clause
ex:-
DEPTNO SAL
---------- ----------
10 2450
10 5000
10 1300
20 2975
20 3000
20 1100
20 800
20 3000
30 1250
30 1500
30 1600
30 950
30 2850
30 1250
14 rows selected.
DEPTNO MAX(SAL)
---------- ----------
30 2850
20 3000
10 5000
Ex:-
DEPTNO SUM(SAL)
---------- ----------
30 9400
20 10875
10 8750
DEPTNO COUNT(*)
---------- ----------
30 6
20 5
10 3
-- waq to display dept.wise with job wise no.of employees are working
10 clerk 1
10 manager 1
.
.
20 clerk 1
20 manager 2
.
.
SQL> SELECT DEPTNO, JOB, COUNT(*) FROM EMP GROUP BY DEPTNO, JOB ORDER BY
DEPTNO;
9 rows selected.
Ex:-
EMP_ATTEN:
----------
EMPID ATTEN_DATE STATUS
E1 01-AUG-23 P
E2 01-AUG-23 P
E3 01-AUG-23 A
E1 02-AUG-23 P
E2 02-AUG-23 A
E3 02-AUG-23 P
E1 03-AUG-23 P
.
.
.
.
-- waq to display each employee howmany days present in the current month
-- waq to display each employee howmany days absent in the current month
-- waq to display each employee howmany days taking leave in the current
month
HAVING <condition> :
--------------------
ex:-
SQL> select job, min(sal) from emp group by job having min(sal) >2000;
JOB MIN(SAL)
--------- ----------
PRESIDENT 5000
MANAGER 2450
ANALYST 3000
SQL> select deptno, count(*) from emp group by deptno having count(*) >
3;
DEPTNO COUNT(*)
---------- ----------
30 6
20 5
ORDER BY CLAUSE :
-----------------
-> It will arrange SELECT output with ORDERED Format either
ASCENDING/DECENDING Order
ex:-
14 rows selected.
14 rows selected.
14 rows selected.
14 rows selected.
Ex:-
EMP_ATTEN:
----------
-- waq to display each employee howmany days present in the current month
-- waq to display each employee howmany days absent in the current month
-- waq to display each employee howmany days taking leave in the current
month
HAVING <condition> :
--------------------
ex:-
SQL> select job, min(sal) from emp group by job having min(sal) >2000;
JOB MIN(SAL)
--------- ----------
PRESIDENT 5000
MANAGER 2450
ANALYST 3000
SQL> select deptno, count(*) from emp group by deptno having count(*) >
3;
DEPTNO COUNT(*)
---------- ----------
30 6
20 5
ORDER BY CLAUSE :
-----------------
-> It will arrange SELECT output with ORDERED Format either
ASCENDING/DECENDING Order
ex:-
14 rows selected.
14 rows selected.
14 rows selected.
14 rows selected.
ii. WHERE
iii. GROUP BY
iv. HAVING
v. SELECT
vi. ORDER BY
CONSTRAINTS :
-------------
-> Constraints are also activated when the tables are manipulated by
other Users or by Other application s/w tools
TYPES OF CONSTRAINTS :
----------------------
bfile, etc.,)
i. column level :
-----------------
-> Constraints are added to next to column name at the time table
creation
-> Constraints are added after declaring all columns at the time of
table creation
ex:-
validations :
-------------
ex:-
validations :
-------------
Testing:
--------
1 row created.
SQL> Insert Into Emp_db values( 1002, 'Srinu', 4000, 20 );
1 row created.
SQL>
SQL> Insert Into Emp_db values( 1003, NULL, 6000, 30 );
Insert Into Emp_db values( 1003, NULL, 6000, 30 )
*
ERROR at line 1:
ORA-01400: cannot insert NULL into ("ORA8PM"."EMP_DB"."ENAME")
1 row created.
ex:-
validations :
-------------
-> Customer id column should not be allow duplicate values
Table creation :
----------------
testing :
---------
1 row created.
1 row created.
1 row created.
ex:-
ex:-
validations :
-------------
Table creation :
----------------
or
testing :
---------
Table created.
1 row created.
Ex:-
validations :
-------------
Table creation :
----------------
Testing :
---------
SQL> Insert into stud_db values( 's1', 'king', 'ix', 89, 78, 98 );
1 row created.
SQL> Insert into stud_db values( 's2', 'Nath', 'x', 67, 89, 68 );
1 row created.
SQL> Insert into stud_db values( 's3', 'Eswar', 'xi', 67, 89, 68 );
Insert into stud_db values( 's3', 'Eswar', 'xi', 67, 89, 68 )
*
ERROR at line 1:
ORA-02290: check constraint (ORA8PM.STUD_DB_CLASS_CHK) violated
SQL> Insert into stud_db values( 's3', 'Eswar', 'x', 102, 89, 68 );
Insert into stud_db values( 's3', 'Eswar', 'x', 102, 89, 68 )
*
ERROR at line 1:
ORA-02290: check constraint (ORA8PM.STUD_DB_MATHS_CHK) violated
SQL> Insert into stud_db values( 's3', 'Eswar', 'x', 92, 105, 68 );
Insert into stud_db values( 's3', 'Eswar', 'x', 92, 105, 68 )
*
ERROR at line 1:
ORA-02290: check constraint (ORA8PM.STUD_DB_PHYS_CHK) violated
SQL> Insert into stud_db values( 's3', 'Eswar', 'x', 92, 95, 101 );
Insert into stud_db values( 's3', 'Eswar', 'x', 92, 95, 101 )
*
ERROR at line 1:
ORA-02290: check constraint (ORA8PM.STUD_DB_CHEM_CHK) violated
validations :
*************
ex:-
-- create a student db table with stud id, stud name, class, date of
joining, fee
validations :
-------------
table creation :
----------------
Testing :
---------
SQL> Insert into stud_db values( '101', 'ABCD', 'IX', DEFAULT, DEFAULT );
1 row created.
1 row created.
-> Once add PRIMARY KEY constraint by default INDEX also added, that is
IMPLICIT INDEX
-> In column level only one column supported PRIMARY KEY Constraint
ex:-
-- create a dept. master table with dept. id, dept.name & loc
validations :
-------------
table creation :
----------------
testing :
---------
1 row created.
1 row created.
1 row created.
1 row created.
EMPLOYEE :
----------
-> To Add Foreign key constraint other table column( REFERENCED TABLE)
COLUMN ( REFERENCED Column ) should be
contain PRIMARY KEY or UNIQUE constraint
-> To add Foreign key constraint to morethan one column that type
constraint is called as COMPOSITE FOREIGN KEY Constraint
-> Foreign key constraint is not supported if any column contains un-
structured datatypes
Ex:-
-- Create a employee table with Employee id, Employee name, Salary &
deptid
Validations :
-------------
Table Creation :
----------------
Testing :
---------
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
SQL> commit;
Commit complete.
6 rows selected.
example 2:-
-----------
ex:-
DELETING RULES :
---------------
ON DELETE CASCADE :
-------------------
-> This option will be added at the time of FOREIGN KEY declaration
ex:-
Table Creation :
----------------
ex:-
Table altered.
step2: Add foreign key constraint on employee(deptid) with ON DELETE
CASCADE OPTION
Table altered.
Testing :
---------
6 rows selected.
1 row deleted.
-> This option also will be added at the time of FOREIGN KEY
declaration
ex:-
Table altered.
Table altered.
Testing :
---------
1 row deleted.
COMPOSITE Constraints :
-----------------------
ex:-
ex:-
-- Create a prod master table with Company Id, Prod Id, Prod Name
validations :
-------------
ex:-
prod:
-----
cid pid pname
---- ---- ------
c1 p1 tea
c1 p2 coffee
c2 p1 tea
c1 p1 soaps -- invalid
ex:-
-- create a sales with sales id, sales date, cid, pid, qty, amt
validations :
--------------
-> selling cid, pids pair should be matched with PROD( cid, pid )
ex:-
sales :
COMPOSITE Constraints :
-----------------------
ex:-
ex:-
-- Create a prod master table with Company Id, Prod Id, Prod Name
validations :
-------------
ex:-
prod:
-----
cid pid pname
---- ---- ------
c1 p1 tea
c1 p2 coffee
c2 p1 tea
c1 p1 soaps -- invalid
ex2:-
std_db:
-------
validation:
-----------
-> std_id , Class pair mandatory and should not be allow duplicate
ex:-
-- create a sales with sales id, sales date, cid, pid, qty, amt
validations :
--------------
-> selling cid, pids pair should be matched with PROD( cid, pid )
ex:-
prod:
-----
cid pid pname
---- ---- ------
c1 p1 tea
c1 p2 coffee
c2 p1 tea
c1 p1 soaps -- invalid
sales :
Table creation :
----------------
Ex:-
validations:
------------
table creation :
----------------
EMP_DB
------
empid ename sal comm
1 kkk 5000 2000
2 mmm 6000 4000
3 xxx 8000 3000 -- returns error message
ex2:-
validations :
-------------
ex:-
UNIQUE :
--------
NOT NULL :
----------
DEFAULT :
---------
CHECK :-
--------
Example :
---------
validations:
------------
validations :
-------------
validations :
-------------
SUB-QUERIES :
-------------
i. ROOT QUERY
i. ROOT QUERY :
---------------
-> the query which is not depends upon another query output for it's
conditional value
-> The query which is depends upon another query output for it's
conditional value
ex:- SELECT * FROM EMP WHERE SAL = ( SELECT MAX(SAL) FROM EMP );
------------------------------
Parent query
-> The query which returns output to it's parent's query is called as
CHILD QUERY
Ex:- SELECT * FROM EMP WHERE SAL = ( SELECT MAX(SAL) FROM EMP
);
------------------------------
Child query
SUB-QUERIES :
-------------
-> Sub-queries are placed in WHERE clause of SELECT, UPDATE and DELETE
statements
-> Sub-queries are also placed in FROM clause and COLUMN_LIST of Outer
Query
-> If Sub-queries are placed in FROM Clause that type of queries are
called as IN-LINE sub-queries / IN-LINE Views
Restrictions :
--------------
-> Sub-queries are not supported by ORDER BY Clause, only IN-LINE SUB-
QUERIES are supported
Adv. :
------
TYPES of SUB-QUERIES :
----------------------
V. SCALAR SUB-QUERIES
ex:- SELECT * FROM EMP WHERE SAL = ( SELECT MAX(SAL) FROM EMP
);
-> In single row sub-queries, Sub-query outputs are compared with >, <,
>=, <=, =, BETWEEN, NOT BETWEEN, etc., operators
ex:-
DEPTNO
------
20
ENAME
----------
SMITH
JONES
SCOTT
ADAMS
FORD
Sub-query :
-----------
SQL> SELECT ENAME FROM EMP WHERE DEPTNO=(SELECT DEPTNO FROM EMP WHERE
ENAME='SMITH');
ENAME
----------
SMITH
JONES
SCOTT
ADAMS
FORD
SQL> select * from emp where sal = ( select max(sal) from emp);
SQL> SELECT * FROM EMP WHERE HIREDATE > ( select hiredate from emp where
ename='FORD');
SQL> SELECT * FROM EMP WHERE SAL > ( select sal from emp where
ename='SCOTT');
-> In single row sub-queries, Sub-query outputs are compared with >, <,
>=, <=, =, BETWEEN, NOT BETWEEN, etc., operators
ex:-
DEPTNO
------
20
ENAME
----------
SMITH
JONES
SCOTT
ADAMS
FORD
Sub-query :
-----------
SQL> SELECT ENAME FROM EMP WHERE DEPTNO=(SELECT DEPTNO FROM EMP WHERE
ENAME='SMITH');
ENAME
----------
SMITH
JONES
SCOTT
ADAMS
FORD
SQL> select * from emp where sal = ( select max(sal) from emp);
SQL> SELECT * FROM EMP WHERE HIREDATE > ( select hiredate from emp where
ename='FORD');
SQL> select * from emp where hiredate = ( select max(hiredate) from emp
);
SQL> select * from emp where hiredate = ( select min(hiredate) from emp
);
SQL> select max(sal) from emp where sal < ( select max(sal) from emp );
MAX(SAL)
----------
3000
SQL> select max(sal) from emp where sal< ( select max(sal) from emp where
sal < ( select max(sal) from emp ) );
MAX(SAL)
----------
2975
SELECT * FROM EMP WHERE SAL >(select max(sal) from emp where
job='CLERK');
SQL> select ename from emp where empno=( select mgr from emp where
ename='SMITH');
ENAME
----------
FORD
SQL> SELECT * FROM EMP WHERE DEPTNO=( select deptno from dept where
loc='NEW YORK' );
ex:-
-- waq to display who are working in NEW YORK and DALLAS Locations
SQL> SELECT * FROM EMP WHERE DEPTNO = ( select deptno from dept where loc
IN ( 'NEW YORK', 'DALLAS' ) );
SELECT * FROM EMP WHERE DEPTNO = ( select deptno from dept where loc IN (
'NEW YORK', 'DALLAS' ) )
*
ERROR at line 1:
ORA-01427: single-row subquery returns more than one row
SQL> SELECT * FROM EMP WHERE DEPTNO IN ( select deptno from dept where
loc IN ( 'NEW YORK', 'DALLAS' ) );
8 rows selected.
SAL
----------
1600
1250
1250
1500
SQL> SELECT * FROM EMP WHERE SAL >ALL ( select sal from emp where
job='SALESMAN' );
6 rows selected.
SELECT * FROM EMP WHERE SAL < ANY ( select sal from emp where
job='MANAGER');
EXISTS :
--------
-> This operator returns BOOLEAN value
Ex:-
SQL> Update emp set sal = sal + sal * 0.5 WHERE EXISTS (select * from emp
where deptno=20);
14 rows updated.
SQL> Update emp set sal = sal + sal * 0.5 WHERE EXISTS (select * from emp
where deptno=50);
0 rows updated.
ex:-
SQL> SELECT * FROM EMP WHERE ( DEPTNO, SAL) IN (SELECT DEPTNO, MAX(SAL)
FROM EMP GROUP BY DEPTNO);
SQL> select ename from emp where ( empno, deptno ) in ( select mgr,
deptno from emp);
ENAME
----------
FORD
BLAKE
KING
JONES
SCOTT
CLARK
6 rows selected.
-> In this Queries, first OUTER QUERY is executed, depends upon output
of OUTER QUERY the INNER QUERY will be executed.
-> if Outer query executes 'n' times then Inner Query also Executes 'n'
times
EMP_DB
------
EMPNO SAL DEPTNO
7369 3000 20 x
7566 5000 30
7839 6000 10
7521 2000 30 x
7499 4000 10 x
7788 8000 20
Ex:-
-- waq to display who are getting morethan their DEPT. Avg. Salaries
7839 6000 10
Select e.empno, e.sal, e.deptno from emp e 5000
where e.sal > ( select avg(sal) from emp
6000 where deptno =
e.deptno );
10
10 - 5000
20 - 5500
30 - 3500
6 rows selected.
DEPTNO AVG(SAL)
------ --------
30 2350
20 3262.5
10 4375
-- waq to display who are getting lessthan their jobs Maximum salaries
8 rows selected.
40 OPERATIONS BOSTON
SELECT D.DEPTNO, D.DNAME, D.LOC FROM DEPT D
WHERE EXISTS ( SELECT * FROM EMP WHERE
DEPTNO = D.DEPTNO );
40
V. SCALAR Sub-Queries :
-----------------------
ex:-
SQL> select empno, ename, job, sal, deptno, ( select sum(sal) from emp )
as total_sal from emp;
14 rows selected.
V. SCALAR Sub-Queries :
-----------------------
ex:-
SQL> select empno, ename, job, sal, deptno, ( select sum(sal) from emp )
as total_sal from emp;
14 rows selected.
14 rows selected.
-- waq to display dept. details and corresponding dept.wise min. and max.
salararies
SQL> Select d.deptno, d.dname, d.loc, ( select nvl( min(sal),0 ) from emp
where deptno=d.deptno) as minsal,
( select nvl( max(sal),0 ) from emp
where deptno=d.deptno) as maxsal
from dept d;
Ex:-
queries :
---------
NESTED SELECT :
---------------
ex:-
SET OPERATORS :
---------------
-> SET OPERATORS are used to join the OUTPUTs of SELECT statements
I. UNION ALL
II. UNION
III. INTERSECT
IV. MINUS
I. UNION ALL :
--------------
-> By using this operator, it displays All records from QUERY1 and
QUERY2
ex:-
JOB
---------
MANAGER
PRESIDENT
CLERK
JOB
---------
CLERK
MANAGER
ANALYST
CLERK
ANALYST
JOB
---------
MANAGER
PRESIDENT
CLERK
CLERK
MANAGER
ANALYST
CLERK
ANALYST
8 rows selected.
ii. UNION :
-----------
-> It displays matching records from Query1 and Query2 at one time and
Un-Matched records from Both Queries
JOB
---------
MANAGER
PRESIDENT
CLERK
JOB
---------
CLERK
MANAGER
ANALYST
CLERK
ANALYST
JOB
---------
ANALYST
CLERK
MANAGER
PRESIDENT
iii. INTERSECT :
----------------
-> It displays matching records from Query1 and Query2 at one time
ex:-
JOB
---------
MANAGER
PRESIDENT
CLERK
JOB
---------
CLERK
MANAGER
ANALYST
CLERK
ANALYST
JOB
---------
CLERK
MANAGER
IV. MINUS :
-----------
ex:-
A = { 1, 2, 4, 6 }
B = { 2, 3, 5, }
A - B = { 1, 4, 6 }
ex:-
JOB
---------
MANAGER
PRESIDENT
CLERK
JOB
---------
CLERK
MANAGER
ANALYST
CLERK
ANALYST
O/P:
-----
PRESIDENT
SQL> SELECT DEPTNO, NULL, MIN(SAL), MAX(SAL) FROM EMP GROUP BY DEPTNO
UNION ALL
SELECT NULL, JOB, MIN(SAL), MAX(SAL) FROM EMP GROUP BY JOB;
8 rows selected.
SQL> select * from emp where sal = ( select max(sal) from emp )
UNION
select * from emp where sal = ( select min(sal) from emp );
PSEUDO COLUMNS :
----------------
I. UID
II. USER
III. SYSDATE
IV. SYSTIMESTAMP
V. ROWID
VI. ROWNUM
VII. LEVEL
VIII. CURRVAL
IX. NEXTVAL
I. UID :
--------
II. USER :
----------
III. SYSDATE :
--------------
ex:-
-- create a login db table with User id, UserName, Login time, Logout
time
table creation :
----------------
Inserting data :
----------------
1 row created.
V. ROWID :
-----------
ex:-
14 rows selected.
Other Examples :
----------------
SQL> select * from emp where rowid = (select min(rowid) from emp);
SQL> select * from emp where rowid = (select max(rowid) from emp);
Emp_db:
-------
Eid ename
--- -----
101 king
102 scott
101 king
103 jones
104 smith
103 jones
Table creation :
-----------------
6 rows selected.
step1 :
-------
MIN(ROWID)
------------------
AAAFCDAABAAALC5AAB
AAAFCDAABAAALC5AAA
AAAFCDAABAAALC5AAE
AAAFCDAABAAALC5AAD
step2 :
-------
SQL> Delete from Emp_db where ROWID NOT IN ( Select min(rowid) from
emp_db group by eid );
2 rows deleted.
EID ENAME
------ --------------------
101 king
102 scott
103 jones
104 smith
SQL> Select * from Emp_db where ROWID NOT IN ( Select min(rowid) from
emp_db group by eid );
EID ENAME
------ --------------------
103 jones
101 king
VI. ROWNUM :
------------
-> ROWNUMs are generated at the time of SELECTING data from DB TABLE
-> On ROWNUM pseudo column >, >=, =, between, not between operators
are not supported
ex:-
14 rows selected.
SQL> select rownum, empno, ename, sal, deptno from emp where deptno=20;
other examples :
----------------
14 rows selected.
12 rows selected.
note: above query is static query, because if table contains 14 rows then
it displays last two records. to display output
dynamically...
SQL> select rownum, Emp.* from emp where rownum<= ( select count(*) from
emp )
MINUS
select rownum, Emp.* from emp where rownum<= ( select count(*)-2
from emp );
SQL> select rownum, emp.* from emp where rownum<=( select count(*)/2 from
emp )
minus
select rownum, emp.* from emp where rownum<=( select (count(*)/2) -1
from emp );
SQL> Select rownum, Sal from ( select rownum ,sal from emp order by sal
desc ) ;
ROWNUM SAL
------ ------
1 7500
2 4500
3 4500
4 4462.5
5 4275
6 3675
7 2400
8 2250
9 1950
10 1875
11 1875
12 1650
13 1425
14 1200
14 rows selected.
SQL> Select rownum, Sal from ( select rownum ,sal from emp order by sal
desc )
where rownum <=5;
ROWNUM SAL
------ ------
1 7500
2 4500
3 4500
4 4462.5
5 4275
SQL> Select rownum, Sal from ( select sal from emp group by sal order by
sal desc )
where rownum <=5;
ROWNUM SAL
------ ------
1 7500
2 4500
3 4462.5
4 4275
5 3675
Note: To Place sub-query in FROM clause that type of queries are called
as IN-LINE SUB-QUERIES / IN-LINE VIEWS
SQL> Select rownum, Sal from ( select rownum ,sal from emp order by sal
desc ) ;
ROWNUM SAL
------ ------
1 7500
2 4500
3 4500
4 4462.5
5 4275
6 3675
7 2400
8 2250
9 1950
10 1875
11 1875
12 1650
13 1425
14 1200
14 rows selected.
SQL> Select rownum, Sal from ( select rownum ,sal from emp order by sal
desc )
where rownum <=5;
ROWNUM SAL
------ ------
1 7500
2 4500
3 4500
4 4462.5
5 4275
SQL> Select rownum, Sal from ( select sal from emp group by sal order by
sal desc )
where rownum <=5;
ROWNUM SAL
------ ------
1 7500
2 4500
3 4462.5
4 4275
5 3675
Note: To Place sub-query in FROM clause that type of queries are called
as IN-LINE SUB-QUERIES / IN-LINE VIEWS
SQL> Select rownum, Sal from ( select sal from emp group by sal order by
sal desc )
where rownum=3;
no rows selected
SQL> Select rownum, Sal from ( select sal from emp group by sal order by
sal desc )
2 group by rownum, sal having rownum=2;
ROWNUM SAL
------ ------
2 4500
SQL> Select rownum, Sal from ( select sal from emp group by sal order by
sal desc )
group by rownum, sal having rownum=5;
ROWNUM SAL
------ ------
5 3675
SQL> Select rownum, Sal from ( select sal from emp group by sal order by
sal desc )
group by rownum, sal having rownum=10;
ROWNUM SAL
------ ------
10 1650
SQL> Select rownum, Sal from ( select sal from emp group by sal order by
sal desc )
group by rownum, sal having rownum=&N;
Enter value for n: 1
ROWNUM SAL
------ ------
1 7500
SQL> /
Enter value for n: 4
ROWNUM SAL
------ ------
4 4275
*
**
***
****
*****
RPAD('*',ROWNUM,'*')
-------------------------------------------------------------------------
---------------------------
*
**
***
****
*****
RPAD('*',ROWNUM,'#')
-------------------------------------------------------------------------
---------------------------
*
*#
*##
*###
*####
VII. LEVEL :
------------
-> It will arrange SELECT statement output with Inverted Tree format
Hierarchical Queries :
**********************
-> These are queries that are executed upon the table that contains
Hierarchical Data
-> If any table contains SELF RELATION / SELF FOREIGN KEY that type of
table contains Hierarchical Data
i. Start With :
---------------
-> Used to filter the data without affecting other rows of the
Hierarchy
Example :
---------
EMP_DB EMP_DB
------ ------
EMPNO ENAME MGR EMPNO ENAME MGR
7369 SMITH 7902 7369 SMITH 7902
7521 JAMES 7698 7521 JAMES 7698
7566 JONES 7839 7566 JONES 7839
7698 BLAKE 7839 7698 BLAKE 7839
7839 KING 7839 KING
7788 SCOTT 7566 7788 SCOTT 7566
7902 FORD 7566 7902 FORD 7566
KING(7839)
JONES(7566) BLAKE(7698)
SMITH(7369)
o/p:
KING
JONES
SCOTT
FORD
SMITH
BLAKE
JAMES
ENAME
----------
KING
JONES
SCOTT
ADAMS
FORD
SMITH
BLAKE
ALLEN
WARD
MARTIN
TURNER
JAMES
CLARK
MILLER
14 rows selected.
SYS_CONNECT_BY_PATH :
---------------------
ORG_CHART
-------------------------------------------------------------------------
--------------------
\KING
\KING\JONES
\KING\JONES\SCOTT
\KING\JONES\SCOTT\ADAMS
\KING\JONES\FORD
\KING\JONES\FORD\SMITH
\KING\BLAKE
\KING\BLAKE\ALLEN
\KING\BLAKE\WARD
\KING\BLAKE\MARTIN
\KING\BLAKE\TURNER
\KING\BLAKE\JAMES
\KING\CLARK
\KING\CLARK\MILLER
14 rows selected.
LEVEL ENAME
------ ----------
1 KING
2 JONES
3 SCOTT
4 ADAMS
3 FORD
4 SMITH
2 BLAKE
3 ALLEN
3 WARD
3 MARTIN
3 TURNER
3 JAMES
2 CLARK
3 MILLER
14 rows selected.
KING
JONES
SCOTT
ADAMS
FORD
SMITH
BLAKE
.
.
.
CLARK
MILLER
VIII. CURRVAL :
IX. NEXTVAL :
---------------
What is a Sequence ?
syn:-
note:-
ex:-
emp_db
-------
eno ( eno_seq )
1
2
3
.
.
5
Table dropped.
Table created.
1 row created.
1 row created.
ENO ENAME
------ --------------------
1 king
2 scott
1 row created.
1 row created.
1 row created.
ENO ENAME
------ --------------------
1 king
2 scott
3 smith
4 allen
5 ward
1 row created.
ENO ENAME
------ --------------------
1 king
2 scott
3 smith
4 allen
5 ward
6 jones
6 rows selected.
table creation :
----------------
sequence :
----------
1 row created.
1 row created.
ACNO CNAME
---------- --------------------
sbi1 Ramesh
sbi2 Anvesh
CURRVAL
-------
6
SQL> SELECT SEQUENCE_NAME FROM USER_SEQUENCES;
SEQUENCE_NAME
------------------------------
ACNO_SEQ
ENO_SEQ
** Dropping Sequences
i. grant
ii. revoke
Grant :
-------
ii. REVOKE :
-----------
Username: SYSTEM
Password: server
example :
---------
-- executed
i. grant
ii. revoke
Grant :
-------
ii. REVOKE :
-----------
Username: SYSTEM
Password: server
example :
---------
-- executed
REVOKE :
--------
i. Commit
ii. Savepoint
iii. Rollback
i. commit :
-----------
ii. SAVEPOINT :
---------------
iii. ROLLBACK :
---------------
-> after COMMIT whatever DML transactions are executed all are undo
example:
--------
-- 14 rows selected
sql> Insert Into emp values( 1001, 'raj', 'clerk', 7839, sysdate, 3000,
100, 10 );
-- 14 rows selected
db objects :
------------
VIEWS :
-------
-> Views doesn't hold any data and it re-presents only STRUCTURE
Adv. :
------
ex:-
connect to DBA :
----------------
username: system
password: server
Grant succeeded.
ORA8PM :
--------
View created.
14 rows selected.
db objects :
------------
VIEWS :
-------
-> View is one of the Virtual DB object
-> Views doesn't hold any data and it re-presents only STRUCTURE
Adv. :
------
ex:-
connect to DBA :
----------------
username: system
password: server
Grant succeeded.
ORA8PM :
--------
14 rows selected.
1 row created.
15 rows selected.
15 rows selected.
ex2:-
View created.
View constraints :
------------------=
ex:-
View created.
1 row created.
ex:-
16 rows selected.
View created.
16 rows selected.
16 rows selected.
SQL> Insert Into empdept values ( 1004, 'aaa', 'clerk', 1500, 10,
'ACCOUNTING', 'NEW YORK');
Insert Into empdept values ( 1004, 'aaa', 'clerk', 1500, 10,
'ACCOUNTING', 'NEW YORK')
*
ERROR at line 1:
ORA-01779: cannot modify a column which maps to a non key-preserved table
** Views doesn't hold any data represents only Structure. here we can
justify with one example :
*************************************************************************
************************
16 rows selected.
16 rows selected.
VIEW_NAME
------------------------------
DEPT10
EMPDEPT
READ_VIEW
V1
** dropping views :
-------------------
-> But, Once drop the BASETABLE(emp) is there Dependent views are
available or not ?
Yes Views are available, but those views doesn't contain any
structure
INDEXES :
---------
-> Indexes are also actived when the tables are manipulated by Other
Users or By other application s/w tools.
INDEXES :
---------
-> Indexes are also actived when the tables are manipulated by Other
Users or By other application s/w tools.
TYPES OF INDEXES :
******************
I. IMPLICIT INDEXES
I. IMPLICIT INDEXES :
---------------------
-> These indexes are created by Oracle automatically
syn:-
i. Normal Indexes :
-------------------
-> These indexes are created on any db column inside the table
ex:-
Index created.
ex:-
ex:-
ex:-
-> Once add Primary key or Unique constraint automatically UNIQUE INDEX
added
syn:-
INDEX_NAME
------------------------------
DEPT_MAS_DEPT_ID_PK
PROD_MAS_CID_PID_PK
EMPNO_IND
** Dropping Indexes :
---------------------
SYNONYMS :
----------
-> Synonyms supports DML, DRL & DESC commands are supported
-> Synonyms provides High Security on DB TABLES Compare to Views
TYPES OF SYNONYMS :
-------------------
i. Private Synonym
i. Private Synonym :
--------------------
Grant succeeded.
In Ora8pm User:
---------------
Synonym created.
3 rows deleted.
13 rows selected.
13 rows selected.
syn:-
ex:-
username : system
password : server
sql> Grant all on ABC to public; -- here only one grant permission all
user can access ABC synonym
16 rows selected.
16 rows selected.
NOTE : Here security provides on Table name and User Name also
16 rows selected.
** dropping synonyms
JOINS :
-------
-> To retrieving data from morethan one table in a single query by
using JOINS
syn of join :-
**************
-> If 'n' tables are joined, there will min. 'n-1' join conditions are
required
-> Join queries are mainly used for to generate reports like Daily
reports, weekly reports, monthly reports,
yearly reports, salary statements, invoices, etc.,
TYPES OF JOINS :
----------------
V. SELF JOIN
-> To write any types of joins, Oracle returns one common error
message is
TABLE ALAISE :
--------------
-> Aliase name is given to next to table name is called as Table Alaise
-> To retrieving data from morethan one table in a single query by using
EQUALITY OPERATOR( = ) in Join Condition is called as
Equi Join
-> To Write Equi Join Queries, Joining tables should be contain atleast
one similar column name and corresponding columns
datatypes should be same.
example :
----------
13 rows selected.
SQL> Select Emp.*, Loc from Emp, Dept Where Emp.Deptno = Dept.Deptno and
loc='NEW YORK';
DNAME COUNT(*)
-------------- --------
RESEARCH 4
-> To retrieving data from morethan one table in a single query by using
EQUALITY OPERATOR( = ) in Join Condition is called as
Equi Join
-> To Write Equi Join Queries, Joining tables should be contain atleast
one similar column name and corresponding columns
datatypes should be same.
example :
----------
13 rows selected.
SQL> Select Emp.*, Loc from Emp, Dept Where Emp.Deptno = Dept.Deptno and
loc='NEW YORK';
DNAME COUNT(*)
-------------- --------
RESEARCH 4
DNAME COUNT(*)
-------------- --------
RESEARCH 4
LOC COUNT(*)
------------- --------
NEW YORK 3
GROUP BY DNAME;
DNAME MAX(SAL)
-------------- --------
SALES 4275
SQL> SELECT MAX(SAL) FROM EMP , DEPT WHERE EMP.DEPTNO = DEPT.DEPTNO AND
DNAME='SALES';
MAX(SAL)
--------
4275
SQL> SELECT DNAME, MAX(SAL), MIN(SAL) FROM EMP , DEPT WHERE EMP.DEPTNO =
DEPT.DEPTNO
AND
DNAME='ACCOUNTING'
GROUP BY DNAME;
Other Examples :
----------------
-- waq to display sbi1 customer current month till date account statement
-- waq to display last month each customer howmany Deposits and Withdraws
are completed
Select Bm.Acno, Cname, TType, Count(*) from Bank_mas BM, Bank_Trans
Bt
where Bm.acno = Bt.Acno
Group by Bm.Acno, Cname,
Ttype
Order by
bm.Acno, Ttype;
-- waq to display SBI1 Customer current month till date howmany withdraws
are completed
-> To retrieving data from morethan one table in a single query without
using Equality Operator is called as
Non-Equi Join
-> In Non-Equi Joins, Join conditions are comparing with >, <, >=, <=,
between, not between, etc., operators
Ex:-
13 rows selected.
13 rows selected.
13 rows selected.
III. Cartesian Join :
---------------------
-> To Retrieving data from morethan one table in a single query without
using any condition is called as Cartesian Join
ex:-
52 rows selected.
-> In this joins, first it displays matching records from Table1 ,Table2
and un-matched records from either table1, or table2 or Both Tables
ex:-
14 rows selected.
13 rows selected.
-> In this Joins, it displays matching records from table1, table2 and
un-matched records from both tables
ex:-
UNION :
-------
-> it displays matching records from query1 and query2 at one time and
un-matched records from both queries
ex:-
A = { 1, 2, 5 }
B = { 2, 4, 6 }
A U B = { 1, 2, 4, 5, 6 }
V. SELF JOIN :
--------------
EMP M EMP E
---- ----
EMPNO ENAME MGR EMPNO ENAME MGR
7369 SMITH 7902 7369 SMITH 7902
7566 JONES 7839 7566 JONES 7839
7698 BLAKE 7839 7698 BLAKE 7839
7839 KING 7839 KING
7902 FORD 7566 7902 FORD 7566
7521 JAMES 7698 7521 JAMES 7698
Example 2 :
***********
13 rows selected.
SUPIROR_NA SUB_ORDINA
---------- ----------
JONES FORD
BLAKE JAMES
BLAKE TURNER
BLAKE MARTIN
BLAKE WARD
BLAKE ALLEN
CLARK MILLER
KING CLARK
KING BLAKE
KING JONES
FORD SMITH
11 rows selected.
8 types Joins
1. Natural Join
2. Join with using
3. Join with ON
4. Inner Join
8. Cross Join
i. Select Empno, Ename, Job, Sal, Deptno, Dname, Loc from Emp Natural
Join Dept;
Note: if joining tables there is no similar column name then Natural Join
returns CROSS join OUTPUT.
ii. Select Empno, Ename, Job, Sal, Deptno, Dname Loc from Emp Join Dept
using (Deptno);
Note: if joining tables there is no similar column name then Natural Join
returns CROSS join OUTPUT.
iii. Select E.Empno, E.Ename, E.Job, E.Deptno, D.Dname, D.Loc from Emp E
Join
Dept D ON(E.Deptno=D.Deptno);
iv. Select E.Empno, E.Ename, E.Job, E.Deptno, D.Dname, D.Loc from Emp E
Inner Join
Dept D ON(E.Deptno=D.Deptno);
vi. Select E.Empno, E.Ename, E.Job, E.Deptno, D.Dname, D.Loc from Emp E
Right Outer Join Dept D ON(E.Deptno=D.Deptno);
vii. Select E.Empno, E.Ename, E.Job, E.Deptno, D.Dname, D.Loc from Emp E
Full Outer Join Dept D ON(E.Deptno=D.Deptno);
viii. Select Empno, Ename, Job, D.Deptno, Dname, Loc from Emp E Cross
Join Dept D
CURRENT_DATE
Purpose
Examples
SESSIONTIMEZONE CURRENT_DATE
--------------- --------------------
-05:00 29-MAY-2000 13:14:03
TimeStamp : Datatype
Example :
-------------
Rename a Column:
Multiple Inserts :
? Supports to insert data into more than one table at a time. But
input must be retrieved from Existing Table.
Conditional Insert :
Insert all
When Deptno<=20 then
into D1 values(deptno, dname, loc)
When Deptno>20 and Deptno<=30 then
into D2 values(deptno,dname,loc)
Else
into D3(Deptno, Dname,Loc) values(Deptno,Dname, Loc)
Select * from Dept;
Merge Statement :
Before MERGING :
Copy_Emp c
Empno Ename Sal Deptno
7839 King 5000 10
7566 AAA 2000 30
7369 Smith 800 30
Emp e
Empno Ename Sal Deptno
7566 Jones 3500 10
7902 Allen 3000 20
7521 James 4000 10
After Merging:
-------------------
Copy_Emp c
Empno Ename Sal Deptno
7839 King 5000 10
7566 JONES 3500 10
7902 Allen 3000 20
7521 James 4000 10
Teacher 1 :
---------------
Teacher 2 :
---------------
NULLIF(Expr1, Expr2) :
• If Expr1 & Expr2 results are same then it Returns Null Value,
otherwise Expr1 Result.
Case in Select :
Temporary Tables :
Commit;
Example 2 :
Table created.
1 row created.
1 row created.
EMPNO ENAME
------ ----------
1001 king
1002 scott
SQL> commit;
Commit complete.
no rows selected
Commit;
Select * from Temp;
Example 2 :
SQL> Create Global Temporary Table Temp
2 ( Empno Number(4), Ename varchar2(10)) on commit Preserve rows;
Table created.
1 row created.
1 row created.
EMPNO ENAME
------ ----------
1001 king
1002 scott
SQL> commit;
Commit complete.
EMPNO ENAME
------ ----------
1001 king
1002 scott
EXTRACT (DATETIME)
EXTRACT extracts and returns the value of a specified datetime field from
a datetime or interval value expression.
EXTRACT(YEARFROMDATE'1998-03-07')
---------------------------------
1998
EXTRACT(DAYFROMSYSDATE)
-----------------------
22
EXTRACT(MONTHFROMSYSDATE)
-------------------------
9
EXTRACT(YEARFROMSYSDATE)
------------------------
2017
The following example selects from the sample table hr.employees all
employees who were hired
after 1998:
-> Write a query to display who are joined in first 15 days from jan and
june in 1981,82, & 83
years.
OLAP FUNCTIONS( ):
ROLLUP:-
A rollup is an extension to the group by clause used to calculate and
return subtotals and grand total as rows of the query efficiently.
It is a group by operation and is used to produce subtotals at any level
of the aggregation. It also calculates a grand total.
If "n" is the number of columns listed in the ROLLUP, there will be n+1
levels of subtotals
Syntax:-
ROLLUP appears in the GROUP BY clause in a SELECT statement. Its form is:
Group by rollup(column1,column2);
or
SELECT ... GROUP BY
ROLLUP(grouping_column_reference_list)
Examples:-
Sql> select deptno,sum(sal) from emp group by rollup(deptno);
Sql> select job,sum(sal) from emp group by rollup(job);
CUBE:-
• it is an extension similar to rollup.
• CUBE enables a SELECT statement to calculate subtotals for all
possible combinations of a group of dimensions.
• It also calculates a grand total.
• If "n" is the number of columns listed in the CUBE, there will be
2n subtotal combinations.
Examples:
Sql> select deptno,job,sum(sal) salary from emp
group by cube(deptno,job);
sql> select job,deptno,sum(sal) salary from emp
group by cube(job,deptno);
Decode function:-
• DECODE is a SQL function that provides similar functionality to an
IF-THEN-ELSE or Case
statement.
• expression is the value to compare search is the value that is
compared against expression
• result is the value returned, if expression is equal to search
• default is optional. If no matches are found, the decode will
return default. If default is omitted, then the decode statement will
return NULL (no matches found).
• The function has no restriction on the input and output data type.
• It is a single row function.
Syntax
The syntax for the decode function is:
decode(expression, search, result [,search,
result]...[,default] )
Examples:-
SQL> SELECT EMPNO, ENAME, JOB, SAL, DEPTNO,
DECODE(DEPTNO,10,'ACCOUNTING',
20,'RESEARCH',
30,'SALES',
40,'OPERATIONS',
'UNKNOWN' ) AS DNAME
FROM EMP;
DEC
---
ODD
Table created.
1 row created.
1 row created.
SQL> commit;
Commit complete.
ACCNO BAL
---------- ----------
sbi1 5000
sbi2 10000
2 rows updated.
ACCNO BAL
---------- ----------
sbi1 10000
sbi2 5000
Ranking functions:-
The different types of ranking functions are
1. Rank() function
2. Dense_rank() function
Rank:-
• The function will compute the rank of each row returned from a
query with respect to the other rows returned by the query, as defined by
the order_by_clause.
• It is possible to have several RANK () OVER functions in a single
SQL statement.
• It returns the rank of items in a group.
• theRANK function can cause non-consecutive rankings if the tested
values are same.
• Rank() leaves a gap in the sequence of rankings in the event of a
tie.
It returns the rank of items in a group.
sql>
DENSE_RANK ( ):
• the DENSE_RANK function will always result in consecutive rankings.
• The DENSE_RANK function acts like the RANK function except that it
assigns consecutive ranks.
Used as an Analytic Function
• As an Analytic function, the DENSE_RANK function returns the rank of
each row of a query with respective to the other rows.
PL/SQL
******
-> PL/SQL supports client side appl.(ex: d2k ) , Server side Appl. and
both Client & Server side applications
What is Block ?
i. Anonymous Block
i. Anonymous Block :
--------------------
-> To Save Anonymous block programs user can explicitely save by using
'SAVE' command
-> All anonymous block programs are start with 'DECLARE' or 'BEGIN'
statement
structure of Anonymous Block :
------------------------------
[Declare
<variable_Declaration>;]
Begin
<exec-statements>;
[Exception Block
<exec-statements>;]
End;
/
Simple BLock :
--------------
Begin
<exec-statements>;
End;
/
-> All Named block programs are start with 'CREATE' command
PL/SQL Datatypes :
------------------
-> PL/SQL supports all SQL datatypes and it supports other datatypes
also
i. SCALAR DATATYPES :
---------------------
-> If any datatype can hold one value that type of datatypes are called
as SCALAR datatypes
-> if any datatype can hold morethan one value is called as Composite
Datatypes
-> these datatypes can hold IMAGES, AUDIO FILES AND video files
V. BOOLEAN DATATYPES :
-----------------------
ex: BOOLEAN
Variable declaration :
----------------------
V_Empid Number(2);
I Number(2) := 1;
Comments :
----------
DBMS_OUTPUT.PUT_LINE( ARG1 ) :
------------------------------
SET SERVEROUTPUT ON :
---------------------
SQL> BEGIN
DBMS_OUTPUT.PUT_LINE('WELCOME TO PL/SQL');
END;
/
SQL> BEGIN
DBMS_OUTPUT.PUT_LINE('WELCOME TO PL/SQL');
END;
/
WELCOME TO PL/SQL
Declare
X Number(4) := 100;
Y Number(4) := 300;
BEGIN
DBMS_OUTPUT.PUT_LINE( ( X + Y ) );
END;
/
400
Declare
X Number(4) := &X;
Y Number(4) := &Y;
BEGIN
DBMS_OUTPUT.PUT_LINE( ( X + Y ) );
END;
/
SQL> Declare
X Number(4) := &X;
Y Number(4) := &Y;
BEGIN
DBMS_OUTPUT.PUT_LINE( ( X + Y ) );
END;
/
Enter value for x: 900
Enter value for y: 600
1500
Declare
X Number(4) := &X;
Y Number(4) := &Y;
BEGIN
DBMS_OUTPUT.PUT_LINE( 'SUM OF TWO NUMBERS = ' || ( X + Y ) );
END;
/
-- Write a pl/sql block two swap two numbers without using Third Variable
Declare
Num1 Number(4) := 100;
Num2 Number(4) := 200;
Begin
dbms_output.put_line( 'Before Swapping two Numbers : ');
dbms_output.put_line( 'NUM1 = '||NUM1 ); -- 100
dbms_output.put_line( 'NUM2 = '||NUM2 ); -- 200
END;
/
SELECT..INTO :
--------------
-> No.of DB Columns should be matched with NO.OF PL/SQL Variables and
corresponding columns datatypes should be same.
syn:-
Example :
---------
Declare
v_ename varchar2(10);
v_sal Number;
Begin
Select Ename, Sal Into v_Ename, v_sal from Emp Where Empno = 7788;
dbms_output.put_line( v_ename );
dbms_output.put_line( v_sal );
End;
/
SCOTT
3000
DECLARE
V_EMPNO NUMBER(4) := &EMPNO;
V_SAL NUMBER(8,2);
V_COMM NUMBER(6,2);
BEGIN
SELECT SAL, COMM INTO V_SAL, V_COMM FROM EMP WHERE EMPNO = V_EMPNO;
DBMS_OUTPUT.PUT_LINE( 'NET SALARY RS.= ' || ( V_SAL + NVL(V_COMM,0) ) );
END;
/
SQL> /
Enter value for empno: 7788
NET SALARY RS.= 3000
Declare
v_empno number(4);
v_ename varchar2(20);
v_job varchar2(20);
v_sal number(5,2);
v_deptno number(2);
Begin
Select Empno, Ename, Job, Sal, Deptno Into
v_empno, v_ename, v_job, v_sal,
v_deptno
From Emp
Where Empno = &Empno;
dbms_output.put_line(' Employee No : '|| v_Empno);
dbms_output.put_line(' Employee Name : '|| v_Ename);
dbms_output.put_line(' Employee Job : '|| v_Job);
dbms_output.put_line(' Employee Salary : '|| v_Sal);
dbms_output.put_line(' Employee Deptno : '|| v_Deptno);
End;
/
SQL> /
Enter value for empno: 7521
Employee No : 7521
Employee Name : WARD
Employee Job : SALESMAN
Employee Salary : 1250
Employee Deptno : 30
REFERENCED DATATYPES :
----------------------
syn:-
<variable_name> <table_name>.<column_name>%type;
ex:-
v_empno emp.empno%type;
example program :
-----------------
Declare
v_empno emp.empno%type;
v_ename emp.ename%type;
v_job emp.job%type;
v_sal emp.sal%type;
v_deptno emp.deptno%type;
Begin
Select Empno, Ename, Job, Sal, Deptno Into
v_empno, v_ename, v_job, v_sal,
v_deptno
From Emp
Where Empno = &Empno;
dbms_output.put_line(' Employee No : '|| v_Empno);
dbms_output.put_line(' Employee Name : '|| v_Ename);
dbms_output.put_line(' Employee Job : '|| v_Job);
dbms_output.put_line(' Employee Salary : '|| v_Sal);
dbms_output.put_line(' Employee Deptno : '|| v_Deptno);
End;
/
syn:-
<variable_name> <table_name>%rowtype;
ex:-
e_rec emp%rowtype;
Example Program :
-----------------
Declare
e emp%rowtype;
Begin
select * into e from emp where empno = &empno;
dbms_output.put_line( e.empno );
dbms_output.put_line( e.ename );
dbms_output.put_line( e.job );
dbms_output.put_line( e.mgr );
dbms_output.put_line( e.hiredate );
dbms_output.put_line( e.sal );
dbms_output.put_line( e.comm );
dbms_output.put_line( e.deptno );
End;
/
Declare
e emp%rowtype;
Begin
select * into e from emp where empno = &empno;
dbms_output.put_line( e.empno ||' '|| e.ename ||' '|| e.job ||' '||e.mgr
||' ' || e.hiredate ||' '||e.sal||' '||
Declare
d dept%rowtype;
Begin
d.deptno := 50;
d.dname := 'MATHS';
d.loc := 'HYD';
Insert into Dept values D;
dbms_output.put_line(' Record Inserted.');
End;
/
Record Inserted.
UPDATE Command :
----------------
Declare
d dept%rowtype;
Begin
d.deptno := 50;
d.dname := 'ENG';
d.loc := 'SEC';
update dept set row = D where deptno = d.deptno;
dbms_output.put_line('record updated.');
end;
/
record updated.
CONTROL STRUCTURES :
--------------------
a. simple if
b. if..else
c. nested if
d. elsif lader
a. simple if :
--------------
syn:-
if <condition> then
<exec-statements>; -- true block
end if;
ex:-
declare
flag boolean := &flag;
Begin
if Flag = true then
dbms_output.put_line('we r in True Block');
end if;
dbms_output.put_line('end of the program');
End;
/
ii. if..else :
--------------
syn:-
if <cond.> then
<exec-statements>; -- True Block
else
<exec-statements>; -- False Block
end if;
example :
---------
Declare
Num Number(4) := &Num;
Begin
if Mod( Num, 2 ) = 0 then
dbms_output.put_line('even');
else
dbms_output.put_line('odd');
end if;
dbms_output.put_line('end of the program');
End;
/
SQL> /
Enter value for num: 12
even
end of the program
iii. Nested if :
----------------
syn:-
if <cond.> then
if <cond.> then
<exec-statements>;
else
<exec-statements>;
end if;
else
if <cond.> then
<exec-statements>;
else
<exec-statements>;
end if;
end if;
iii. Nested if :
----------------
syn:-
if <cond.> then
if <cond.> then
<exec-statements>;
else
<exec-statements>;
end if;
else
if <cond.> then
<exec-statements>;
else
<exec-statements>;
end if;
end if;
Declare
v_emptype char(1) := '&emp_type'; -- 't'
v_exp Number(4) := &exp; -- 9
Begin
if v_emptype='p' then
if v_exp >=10 then
dbms_output.put_line(' Employ will get 50% Bonus.');
else
dbms_output.put_line(' Employ will get 30% Bonus.');
end if;
else
if v_exp >=10 then
dbms_output.put_line(' Employ will get 20% Bonus.');
else
dbms_output.put_line(' Employ will get 15% Bonus.');
end if;
end if;
End;
/
SQL> /
Enter value for emp_type: p
Enter value for exp: 9
Employ will get 30% Bonus.
SQL> /
Enter value for emp_type: t
Enter value for exp: 14
Employ will get 20% Bonus.
SQL> /
Enter value for emp_type: t
Enter value for exp: 3
Employ will get 15% Bonus.
syn:-
if <cond.> then
<exec-statements>;
elsif <cond.> then
<exec-statements>;
elsif <cond.> then
<exec-statements>;
.
.
else
<exec-statements>;
End if;
Example :
---------
Declare
v_empno emp.empno%type := &empno;
v_deptno emp.deptno%type;
Begin
Select deptno into v_deptno from emp where empno = v_empno;
if v_deptno=10 then
dbms_output.put_line('ACCOUNTING DEPT.');
elsif v_deptno=20 then
dbms_output.put_line('RESEARCH DEPT.');
elsif v_deptno=30 then
dbms_output.put_line('SALES DEPT.');
elsif v_deptno=40 then
dbms_output.put_line('OPERATIONS DEPT.');
else
dbms_output.put_line('UNKNOWN DEPT.');
end if;
End;
/
SQL> /
Enter value for empno: 7369
RESEARCH DEPT.
SQL> /
Enter value for empno: 7521
SALES DEPT.
i. CASE
syn:-
CASE <variable/expression>
WHEN <cond.> then
<exec-statements>;
WHEN <cond.> then
<exec-statements>;
WHEN <cond.> then
<exec-statements>;
ELSE
<exec-statements>;
END CASE;
Example :
---------
Declare
color char(1) := '&color';
Begin
Case color
when 'r' then
dbms_output.put_line('u r selected red color.');
when 'y' then
dbms_output.put_line('u r selected yellow color.');
when 'b' then
dbms_output.put_line('u r selected black color.');
else
dbms_output.put_line('your selection is wrong plz. try again....');
end case;
End;
/
SQL> /
Enter value for color: b
u r selected black color.
SQL> /
Enter value for color: x
your selection is wrong plz. try again....
-> the statements are executed 'n' no.of times until given condition
become TRUE / FALSE
i. simple loop
i. simple loop :
-----------------
syn:-
Loop
<exec-statements>;
End Loop;
example:
--------
Begin
Loop
dbms_output.put_line( 'Welcome' );
End Loop;
End;
/
i. if <cond.> then
Exit;
end if;
example :
---------
Declare
i number(4) := 1;
Begin
Loop
if i >10 then
exit;
end if;
dbms_output.put_line('Welcome');
i := i + 1;
End Loop;
dbms_output.put_line('end of the program');
End;
/
Welcome
Welcome
Welcome
Welcome
Welcome
Welcome
Welcome
Welcome
Welcome
Welcome
end of the program
syn 2:-
example :
---------
Declare
i number(4) := 1;
Begin
Loop
EXIT WHEN i >10;
dbms_output.put_line('Welcome');
i := i + 1;
End Loop;
dbms_output.put_line('end of the program');
End;
/
Welcome
Welcome
Welcome
Welcome
Welcome
Welcome
Welcome
Welcome
Welcome
Welcome
end of the program
syn:-
WHILE ( <cond.> )
LOOP
<exec-statements>;
Incr/Decr;
END LOOP;
Example :
Declare
i Number(4) :=1;
Begin
While( i <=10 )
Loop
dbms_output.put_line( i );
i := i + 1;
End Loop;
End;
/
1
2
3
4
5
6
7
8
9
10
syn:-
WHILE ( <cond.> )
LOOP
<exec-statements>;
Incr/Decr;
END LOOP;
Example :
Declare
i Number(4) :=1;
Begin
While( i <=10 )
Loop
dbms_output.put_line( i );
i := i + 1;
End Loop;
End;
/
1
2
3
4
5
6
7
8
9
10
declare
i Number(4) := 10;
Begin
While( i >=1 )
Loop
dbms_output.put_line( i );
i := i - 1;
End Loop;
End;
/
10
9
8
7
6
5
4
3
2
1
5*1=5
5*2=10
.
.
5*10=50
Declare
N Number(4) := &N; -- 5
i Number(4) := 1;
Begin
While( i <= 10 )
Loop
dbms_output.put_line( N || '*' || i || '=' || (N*i) );
i := i + 1;
End Loop;
End;
/
SQL> /
Enter value for n: 19
19*1=19
19*2=38
19*3=57
19*4=76
19*5=95
19*6=114
19*7=133
19*8=152
19*9=171
19*10=190
syn:-
example :
---------
Begin
FOR I in 1..10
LOOP
dbms_output.put_line( i );
END LOOP;
END;
/
1
2
3
4
5
6
7
8
9
10
-- REVERSE ORDER
Begin
FOR I in REVERSE 1..10
LOOP
dbms_output.put_line( i );
END LOOP;
END;
/
10
9
8
7
6
5
4
3
2
1
Example :
---------
declare
N Number(4) := &N;
begin
if N >0 then
goto pos;
else
goto neg;
end if;
<<pos>>
dbms_output.put_line( 'Given No. is Positive.');
goto endl;
<<neg>>
dbms_output.put_line( 'Given No. is Negative.');
goto endl;
<<endl>>
dbms_output.put_line( 'End of the Program. ');
End;
/
SQL> /
Enter value for n: -4
Given No. is Negative.
End of the Program.
CURSORS :
---------
declare
v_ename emp.ename%type;
begin
Select ename into v_ename from emp where deptno=10;
dbms_output.put_line( v_ename );
End;
/
declare
*
ERROR at line 1:
ORA-01422: exact fetch returns more than requested number of rows
ORA-06512: at line 4
note: v_ename variable can hold only one value at a time
CURSORS :
----------
-> In pl/sql block whenever SELECT statement returns more than one row
then to use CURSORS
I. STATIC CURSOR
I. STATIC CURSOR :
------------------
a. Explicit Cursors :
---------------------
Cursor Operations :
-------------------
i. Declaring cursor :
---------------------
syn:-
CURSOR <cursor_name>
Is
<Select statement>;
CURSOR ATTRIBUTES :
-------------------
syn:-
<cursor_name>%<attribute>;
i. %isopen :
------------
ii. %found :
------------
iii. %notfound :
----------------
iv. %rowcount :
---------------
Example :
----------
-- pl/sql block for to demonistrate cursor operations & attributes
Declare
cursor my_cur is select ename from emp;
v_ename emp.ename%type;
Begin
Open my_cur;
if my_cur%isopen then
dbms_output.put_line('Cursor Opened Successfully.');
end if;
Fetch my_cur into v_ename;
dbms_output.put_line( v_ename );
Fetch my_cur into v_ename;
dbms_output.put_line( v_ename );
Fetch my_cur into v_ename;
dbms_output.put_line( v_ename );
close my_cur;
end;
/
NOTE: above program displays first three employee names only. To display
all employee names then to use
cursor using LOOPs
-- write a cursor program to display all employee names from emp table
Declare
cursor my_cur is select ename from emp;
v_ename emp.ename%type;
Begin
Open my_cur;
if my_cur%isopen then
dbms_output.put_line('Cursor Opened Successfully.');
end if;
LOOP
Fetch my_cur into v_ename;
EXIT WHEN MY_CUR%NOTFOUND;
dbms_output.put_line( v_ename );
END LOOP;
Close my_cur;
End;
/
Table creation :
----------------
program :
---------
declare
cursor e_cur is select empno, job, sal from emp;
v_empno emp.empno%type;
v_job emp.job%type;
v_sal emp.sal%type;
v_incr_sal Number;
Begin
Open e_cur;
Loop
fetch e_cur into v_empno, v_job, v_sal;
exit when e_cur%notfound;
if v_job in ( 'ANALYST','MANAGER' ) then
v_incr_sal := v_sal * 0.3;
elsif v_job in ( 'SALESMAN','CLERK' ) then
v_incr_sal := v_sal * 0.2;
else
v_incr_sal := 0;
end if;
insert into emp_audit values ( v_empno, sysdate, v_incr_sal );
Update emp set sal = sal + v_incr_sal where empno = v_empno;
End Loop;
dbms_output.put_line( 'Salaries Incremented successfully.');
Close e_cur;
End;
/
13 rows selected.
13 rows selected.
Declare
cursor c1 is select sal from emp order by sal desc;
v_sal emp.sal%type;
Begin
Open c1;
fetch c1 into v_sal;
While( c1%rowcount<=5 )
Loop
dbms_output.put_line( v_sal );
fetch c1 into v_sal;
End Loop;
close c1;
End;
/
7500
5850
5801.25
5557.5
4777.5
SQL%FOUND :
-----------
SQL%NOTFOUND:
-------------
SQL%ROWCOUNT :
--------------
SQL%FOUND :
-----------
SQL%NOTFOUND:
-------------
SQL%ROWCOUNT :
--------------
Ex:-
ex2:-
Begin
Update emp set sal = sal + 100 where deptno=50;
if SQL%FOUND then
dbms_output.put_line( 'Employ Salaries Incremented Successfully.');
else
dbms_output.put_line( 'Employ Records Not Found.');
end if;
End;
/
-> SELECT statement will be provided at the time of opening the cursor
syn:-
ex:-
declare
TYPE R_CUR IS REF CURSOR;
v_cur r_cur;
v_empno emp.empno%type;
v_exp number;
v_hiredate emp.hiredate%type;
v_dname dept.dname%type;
Begin
Open v_cur for select empno, hiredate from emp;
loop
fetch v_cur into v_empno, v_hiredate;
exit when v_cur%notfound;
v_exp := round( (sysdate - v_hiredate)/365);
dbms_output.put_line( v_empno || ' Employee Experience is ' ||
v_exp|| ' Years.');
end loop;
close v_cur;
dbms_output.put_line('*********************************************');
open v_cur for select empno, dname from emp, dept where emp.deptno =
dept.deptno;
loop
fetch v_cur into v_empno, v_dname ;
exit when v_cur%notfound;
dbms_output.put_line( v_empno || ' Employee working in ' || v_dname
|| ' Dept.');
end loop;
close v_cur;
End;
/
iii. after fetch the all records then FOR LOOP close the
cursor
ex:-
Declare
cursor c1 is select * from emp;
Begin
For i in c1
Loop
dbms_output.put_line( i.empno ||' '||i.ename||' '||i.job||'
'||i.hiredate||' '||i.sal ||' '||i.deptno );
End loop;
End;
/
SQL> declare
2 v_ename emp.ename%type;
3 begin
4 select ename into v_ename from emp where empno=7788;
5 dbms_output.put_line( v_ename );
6 End;
7 /
SCOTT
SQL> declare
2 v_ename emp.ename%type;
3 begin
4 select ename into v_ename from emp where empno=9000;
5 dbms_output.put_line( v_ename );
6 End;
7 /
declare
*
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at line 4
EXCEPTION HANDLING :
--------------------
I. PRE-DEFINED Exceptions
I. PRE-DEFINED Exceptions :
---------------------------
EXCEPTION HANDLING :
--------------------
I. PRE-DEFINED Exceptions
I. PRE-DEFINED Exceptions :
---------------------------
-> While executing the program oracle returns some common error
messages are called as pre-defined exceptions
ex:-
SQL> declare
v_ename emp.ename%type;
begin
select ename into v_ename from emp where empno=9000;
dbms_output.put_line( v_ename );
Exception
when NO_DATA_FOUND then
dbms_output.put_line( 'Employee Record Not Found.');
End;
/
example 2:
----------
Declare
v_ename emp.ename%type;
Begin
select ename into v_ename from emp;
dbms_output.put_line( v_ename );
End;
/
Declare
*
ERROR at line 1:
ORA-01422: exact fetch returns more than requested number of rows
ORA-06512: at line 4
Declare
v_ename emp.ename%type;
Begin
select ename into v_ename from emp;
dbms_output.put_line( v_ename );
Exception
when TOO_MANY_ROWS then
dbms_output.put_line( 'Morethan one record found.');
End;
/
Example 3 :
***********
ZERO_DIVIDE :
-------------
Begin
dbms_output.put_line( 'Division of Two Numbers = '|| ( &x / &y ) );
exception
when zero_divide then
dbms_output.put_line('Divisor should not be equals to 0.');
End;
/
Enter value for x: 10
Enter value for y: 2
Division of Two Numbers = 5
SQL> /
Enter value for x: 10
Enter value for y: 0
Divisor should not be equals to 0.
Example 4 :
-----------
VALUE_ERROR :
-------------
Declare
str varchar2(5);
Begin
str := 'NARESH IT';
dbms_output.put_line( str );
End;
/
Declare
*
ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error: character string buffer too
small
ORA-06512: at line 4
Declare
str varchar2(5);
Begin
str := 'NARESH IT';
dbms_output.put_line( str );
Exception
when VALUE_ERROR then
dbms_output.put_line( 'Inputing data is Exceeds given variable
size...');
End;
/
Example 5:
----------
INVALID_NUMBER :
----------------
SQL> Begin
Insert into dept values ( 'MATHS', 50, 'HYD');
Exception
when INVALID_NUMBER then
dbms_output.put_line( 'Insert Appropriate Data into Table.');
END;
/
Example 6 :
-----------
CURSOR_ALREADY_OPEN :
---------------------
Example :
---------
Declare
cursor c1 is select ename from emp;
Begin
open c1;
open c1;
close c1;
End;
/
Declare
*
ERROR at line 1:
ORA-06511: PL/SQL: cursor already open
ORA-06512: at line 2
ORA-06512: at line 5
Declare
cursor c1 is select ename from emp;
Begin
open c1;
open c1;
close c1;
Exception
when cursor_already_open then
dbms_output.put_line( 'First close the cursor without re-open');
End;
/
a. RAISE
b. RAISE_APPLICATION_ERROR
a. RAISE :
-----------
-> It is one of the pre-defined procedures and used throws user defined
exception name into exception block
syn:-
RAISE <user-defined_exception-name>;
b. RAISE_APPLICATION_ERROR :
----------------------------
-> This procedure is used to displays ERROR messages with ERROR code
syntax:
-------
RAISE_APPLICATION_ERROR( user_defined_error_code,
user_defined_error_message );
example :
---------
Declare
*
ERROR at line 1:
ORA-20001: Week-Ends Transactions are not allowed.
ORA-06512: at line 11
a. RAISE
b. RAISE_APPLICATION_ERROR
a. RAISE :
-----------
-> It is one of the pre-defined procedures and used throws user defined
exception name into exception block
syn:-
RAISE <user-defined_exception-name>;
b. RAISE_APPLICATION_ERROR :
----------------------------
-> This procedure is used to displays ERROR messages with ERROR code
RAISE_APPLICATION_ERROR( user_defined_error_code,
user_defined_error_message );
example :
---------
Declare
holiday Exception;
Begin
if to_char(sysdate,'dy') in ( 'sat','sun') then
RAISE holiday;
else
dbms_output.put_line('DML Transactions are Allows.');
end if;
Exception
when holiday then
raise_application_error( -20001, 'Week-Ends Transactions are not
allowed.');
End;
/
Declare
*
ERROR at line 1:
ORA-20001: Week-Ends Transactions are not allowed.
ORA-06512: at line 11
validations :
-------------
Declare
v_empno emp.empno%type := &Empno;
v_job emp.job%type;
ABC Exception;
Begin
select job into v_job from emp where empno = v_empno;
if V_Job != 'SALESMAN' then
RAISE ABC;
else
dbms_output.put_line('Employee is Eliible for COMMISSION.');
end if;
Exception
when ABC THEN
RAISE_APPLICATION_ERROR(-20001, 'Employee is Not Eligible for
Commission.');
End;
/
SQL> /
Enter value for empno: 7521
Employee is Eliible for COMMISSION.
PRAGMA EXCEPTION_INIT :
-----------------------
syn:-
example :
---------
Declare
Duplicates_Found Exception;
Pragma Exception_Init( Duplicates_Found, -00001 );
Begin
Insert Into Dept Values ( &deptno, '&dname', '&loc' );
dbms_output.put_line('record inserted.');
Exception
when duplicates_found then
raise_application_error(-20001, 'Given Dept. No. Already Exists....');
End;
/
Enter value for deptno: 50
Enter value for dname: MATHS
Enter value for loc: HYD
record inserted.
SQL> Declare
2 Duplicates_Found Exception;
3 Pragma Exception_Init( Duplicates_Found, -00001 );
4 Begin
5 Insert Into Dept Values ( &deptno, '&dname', '&loc' );
6 dbms_output.put_line('record inserted.');
7 Exception
8 when duplicates_found then
9 raise_application_error(-20001, 'Given Dept. No. Already
Exists....');
10 End;
11 /
Enter value for deptno: 50
Enter value for dname: ENG
Enter value for loc: SEC
Declare
*
ERROR at line 1:
ORA-20001: Given Dept. No. Already Exists....
ORA-06512: at line 9
Example :
=========
Declare
Duplicates_Found Exception;
Pragma Exception_Init( Duplicates_Found, -00001 );
Nulls_Found Exception;
Pragma Exception_Init( Nulls_Found, -01400 );
Begin
Insert Into Dept Values ( &deptno, '&dname', '&loc' );
dbms_output.put_line('record inserted.');
Exception
when duplicates_found then
raise_application_error(-20001, 'Given Dept. No. Already Exists....');
when NULLS_FOUND then
raise_application_error(-20002, 'Deptno Column Value is
Mandatory....');
End;
/
Example :
---------
Declare
v_ename emp.ename%type;
Begin
select ename into v_ename from emp;
dbms_output.put_line( v_ename );
exception
when no_data_found then
raise_application_error(-20001, 'Given Employee Record Not
Exists,....');
when OTHERS then
dbms_output.put_line( 'Raising Error Code : ' || SQLCODE);
dbms_output.put_line( 'Raising Error Message : ' || SQLERRM);
raise_application_error(-20002, 'Default Exception is Raised.');
end;
/
SUB-PROGRAMS :
--------------
Adv. :
------
a. Easy to Understand
i. Stored Procedure
i. Stored Procedure :
---------------------
ii. re-usability
-> All created stored procedure Bodies are stored in USER_SOURCE table &
Procedure Names are stored in USER_OBJECTS table
Syn:-
Example :
---------
on SQL prompt :
---------------
Example :
---------
syn:-
Begin
<Procedure_Name>;
End;
/
example :
---------
SQL> Begin
my_proc;
End;
/
TEXT
----------------------------------------------------------------------
Procedure my_proc
is
Begin
dbms_output.put_line( 'Welcome to Stored Procedures....');
End my_proc;
OBJECT_NAME
-------------------------------------------------------------------------
----------------
MY_PROC
LINE/COL ERROR
-------- ----------------------------------------------------------------
-
7/1 PLS-00103: Encountered the symbol "END" when expecting one of
the
following:
:= . ( % ;
The symbol ";" was substituted for "END" to continue.
Procedure created.
note :- Above program returns same output every time because procedures
are compiled only one time. To take values at run-time then
to use Procedures with Parameters
-> Procedures are supports three types of Parameter Modes like,... IN,
OUT, IN OUT
example :
---------
-> Procedures are supports three types of Parameter Modes like,... IN,
OUT, IN OUT
example :
---------
Calling Procedure :
-------------------
*
ERROR at line 1:
ORA-20001: Employ Record Not Found.
ORA-06512: at "ORA8PM.EMP_REC", line 10
ORA-06512: at line 1
6 rows selected.
Ex:-
i. IN
ii. OUT
iii. IN OUT
i. IN :
--------
ex:-
LINE/COL ERROR
-------- ----------------------------------------------------------------
-
5/3 PL/SQL: Statement ignored
5/3 PLS-00363: expression 'X' cannot be used as an assignment target
ii. OUT :
---------
-> Generally Procedures MAY/MAY NOT return values. But, by using OUT
parameter mode it returns output
Example :
---------
-- Stored Procedure for to find sum of two given number and return
output
Procedure created.
NOTE: To declare variables on SQL PROMT that type variables are called as
BIND / GLOBAL VARIABLES
i. IN
ii. OUT
iii. IN OUT
i. IN :
--------
ex:-
LINE/COL ERROR
-------- ----------------------------------------------------------------
-
5/3 PL/SQL: Statement ignored
5/3 PLS-00363: expression 'X' cannot be used as an assignment target
ii. OUT :
---------
-> Generally Procedures MAY/MAY NOT return values. But, by using OUT
parameter mode it returns output
Example :
---------
-- Stored Procedure for to find sum of two given number and return
output
Procedure created.
RES
------
900
NOTE: To declare variables on SQL PROMT that type variables are called as
BIND / GLOBAL VARIABLES
Ex2:-
V_JOB
-------------------------------------------------------------------------
-------------------
PRESIDENT
declare
v_job emp.job%type;
Begin
Emp_Job( 7839, v_job ); -- calling procedure
dbms_output.put_line( 'Given Employee Job is ' || v_job );
End;
/
declare
v_job emp.job%type;
Begin
Emp_Job( &Empno, v_job ); -- calling procedure
dbms_output.put_line( 'Given Employee Job is ' || v_job );
End;
/
Enter value for empno: 7521
Given Employee Job is SALESMAN
SQL> /
Enter value for empno: 7902
Given Employee Job is ANALYST
Declare
v_empno emp.empno%type := &empno;
v_ename emp.ename%type;
v_job emp.job%type;
v_sal emp.sal%type;
v_deptno emp.deptno%type;
Begin
Emp_Find( v_empno, v_ename, v_job, v_sal, v_deptno ); -- calling
procedure
dbms_output.put_line( 'Emp No : '||v_empno);
dbms_output.put_line( 'Emp Name : '||v_ename);
dbms_output.put_line( 'Emp Job : '||v_job);
dbms_output.put_line( 'Emp Salary : '||v_sal );
dbms_output.put_line( 'Emp Deptno : '||v_deptno);
End;
/
Table Creation :
----------------
Validations :
-------------
Stored Procedure :
------------------
Table Creation :
----------------
Validations :
-------------
Stored Procedure :
------------------
CALLING PROCEDURE :
-------------------
declare
status varchar2(100);
begin
user_reg_proc( &user_name, &password, &cnf_password, &Role, status ); -
- calling procedure
dbms_output.put_line( Status );
End;
/
SQL> /
Enter value for user_name: 'scott'
Enter value for password: 'scot123'
Enter value for cnf_password: 'scott123'
Enter value for role: 'employ'
Enter and Confirm Passwords should be Sampe.
SQL> /
Enter value for user_name: 'scott'
Enter value for password: 'scott123'
Enter value for cnf_password: 'scott123'
Enter value for role: 'employ'
User Created Successfully.
SQL> /
Enter value for user_name: 'smith'
Enter value for password: 'smith'
Enter value for cnf_password: 'smith'
Enter value for role: 'admin
ERROR:
ORA-01756: quoted string not properly terminated
SQL> /
Enter value for user_name: 'smith'
Enter value for password: 'smith'
Enter value for cnf_password: 'smith'
Enter value for role: 'admin'
Min. Length of Password is 6 characters.
PL/SQL procedure successfully completed.
SQL>
SQL>
SQL> /
Enter value for user_name: 'smith'
Enter value for password: 'smith123'
Enter value for cnf_password: 'smith123'
Enter value for role: 'guest'
Invalid Role!!!!
v_cnt Number;
Begin
select count(*) Into v_cnt from User_Details where user_name =
p_user_name
and
password = p_password;
if v_cnt > 0 then
p_status := 'Login Successfully ';
else
p_status := 'Invalid UserName/Password';
end if;
End Login_Proc;
/
calling program :
-----------------
declare
status varchar2(100);
Begin
login_proc( &user_name, &password , status ); -- calling procedure
dbms_output.put_line( status );
End;
/
SQL>
SQL> /
Enter value for user_name: 'scott'
Enter value for password: 'scott123'
Login Successfully
SQL> /
Enter value for user_name: 'king'
Enter value for password: 'king'
Invalid UserName/Password
SQL> /
Enter value for user_name: 'smith'
Enter value for password: 'smith123'
Invalid UserName/Password
-> While calling the procedures if we are not passing any value to
parameter by default
procedures takes specified DEFAULT value
ex:-
-> While calling the procedures if we are not passing any value to
parameter by default
procedures takes specified DEFAULT value
ex:-
-- stored procedure for to insert data into DEPT table
6 rows selected.
Note: in the 2nd Execution Dept. Name is taken as 'HYD' & loc taken as
'Unknown'. To overcome this problem Procedures are supports
NOTATIONS concept.
NOTATIONS :
-----------
i. Positional Notation
i. Positional Notation :
------------------------
ex:-
SQL> Exec Dept_Proc( P_LOC => 'HYD', P_DEPTNO=> 70, P_DNAME => 'ENG' );
record inserted.
7 rows selected.
-> Both Positional and Named Notations are called as MIXED NOTATIONS
ex:-
8 rows selected.
TEXT
-------------------------------------------------------------------------
---------------------------
procedure dept_proc
( p_deptno dept.deptno%type,
p_dname dept.dname%type default 'Unknown',
p_loc dept.loc%type default 'Unknown'
)
is
Begin
Insert Into dept values ( p_deptno, p_dname, p_loc );
dbms_output.put_line('record inserted.');
End dept_Proc;
10 rows selected.
OBJECT_NAME
-------------------------------------------------------------------------
-----------------
DEPT_PROC
LOGIN_PROC
EMP_DEL_REC
EMP_UPD_PROC
DEPT_INS_PROC
EMP_REC
USER_REG_PROC
EMP_FIND
EMP_JOB
ADD_PROC
MY_PROC
11 rows selected.
** Dropping Procedures
syn:- Drop Procedure <Procedure_Name>;
-> According to client requirement developer write with his own logic
and own function name is called as user-defined functions.
i. modularity
ii. re-usability
syntax :-
Examples :-
Calling Function :
------------------
on SQL Prompt :
---------------
method 1 :
----------
SIMPLE_INT(1000,2,10)
---------------------
200
method 2 :
----------
INTEREST
----------
200
method 3 :
----------
declare
interest number;
begin
select simple_int(1000,2,10) into Interest from dual;
dbms_output.put_line( 'Simple Interest = '||Interest );
End;
/
method 4 :
----------
declare
interest number;
begin
interest := simple_int(1000,2,10);
dbms_output.put_line( 'Simple Interest = '||Interest );
End;
/
method 5 :
----------
Begin
dbms_output.put_line( 'Simple Interest = '||Simple_Int(1000,2,10) );
End;
/
Example 2:
----------
EMP_NETSAL(7839)
-----------------------------------------
7839 Employee Net Salary Rs.6000
EMP_NETSAL(7521)
-----------------------------------------
7521 Employee Net Salary Rs.1750
13 rows selected.
Example 3 :
-----------
Begin
if emp_find( &empno ) = True then
dbms_output.put_line( 'Employ Record Found.');
else
dbms_output.put_line( 'Employ Record Not Found.');
end if;
End;
/
SQL> /
Enter value for empno: 9000
Employ Record Not Found.
Table creation :
----------------
Table creation :
----------------
13 rows selected.
13 rows selected.
-- write a user defined function to find first name from given name
FNAME('RAMAKRISHNARAJU')
---------------------------------------------------------------------
RAMA
FNAME('KRISHNARAJU')
---------------------------------------------------------------------
KRISHNA
OBJECT_NAME
-------------------------------------------------------------------------
---
EMP_FIND
EMP_NETSAL
SIMPLE_INT
EMP_EXP
FNAME
TEXT
-------------------------------------------------------------------------
--------------------------
procedure emp_incr_Proc
is
Cursor e_cur is select empno, sal from emp;
v_empno emp.empno%type;
v_sal emp.sal%type;
v_incr_sal Number;
Begin
open e_cur;
loop
fetch e_cur into v_empno, v_sal; -- 7369, 900
exit when e_cur%notfound;
if emp_exp( v_empno ) >=10 then
v_incr_sal := v_sal * 0.5;
else
v_incr_sal := v_sal * 0.3;
end if;
Insert into Employ_Incr values ( v_empno, sysdate, emp_exp(v_empno),
v_incr_sal );
Update emp set sal = sal + v_incr_sal where empno = v_empno;
end loop;
close e_cur;
dbms_output.put_line( 'Employ Salary Incremented Successfully....');
End emp_incr_Proc;
22 rows selected.
** Dropping functions
PACKAGES :
**********
-> Packges are not supported parameters and It doesn't return any
values
-> All created package names are stored in USER_OBJECTS & Bodies are
stored USER_SOURCE table
I. PRE-DEFINED PACKAGES
a. Package Specification
b. Package Body
a. Package Specification :
--------------------------
b. Package body :
------------------
Ex:-
Package specification :
-----------------------
Package body :
--------------
End my_pack;
/
MY_PACK.MUL_FUN(100,200)
------------------------
20000
-> These functions are applicable for each and every column values
-> Column Level Functions are classified into 3 types
i. NUMBER Functions
i. NUMBER Functions :
---------------------
ABS() :
-------
ex:-
ABS(-100)
----------
100
100
100
100
100
100
100
100
100
100
100
100
100
100
14 rows selected.
ABS(-100)
----------
100
100
100
100
D
-
X
SQL>
SQL> select abs(-100) from dual;
ABS(-100)
----------
100
note: DUAL is one of the ORACLE pre-defined function and it contains one
record. So, our function is calling only one time.
SQRT() :
--------
ex:-
ABS(-100)
----------
100
SQRT(25)
----------
5
MOD() :
-------
MOD(10,2)
----------
0
MOD(10,3)
----------
1
SIGN(-1000)
-----------
-1
SIGN(1000)
----------
1
SIGN(0)
----------
0
SIN() :
-------
cos() :
-------
tan() :
-------
ROUND() :
---------
ex:-
ROUND(16.78)
------------
17
ROUND(16.48)
------------
16
-- to display after decimal part single digit
ROUND(16.796,1)
---------------
16.8
ROUND(16.746,2)
---------------
16.75
TRUNC :-
--------
ex:-
TRUNC(16.78)
------------
16
TRUNC(16.758,1)
---------------
16.7
TRUNC(16.987,2)
---------------
16.98
16.35 -> 16
16.65 -> 17
EMPNO SAL/30
---------- ----------
7369 26.6666667
7499 53.3333333
7521 41.6666667
7566 99.1666667
7654 41.6666667
7698 95
7782 81.6666667
7788 100
7839 166.666667
7844 50
7876 36.6666667
7900 31.6666667
7902 100
7934 43.3333333
14 rows selected.
EMPNO ROUND(SAL/30)
---------- -------------
7369 27
7499 53
7521 42
7566 99
7654 42
7698 95
7782 82
7788 100
7839 167
7844 50
7876 37
7900 32
7902 100
7934 43
14 rows selected.
EMPNO EXPERIENCE
---------- ----------
7369 42.9
7499 42.7
7521 42.7
7566 42.6
7654 42.1
7698 42.5
7782 42.4
7788 40.9
7839 41.9
7844 42.1
7876 40.8
7900 41.9
7902 41.9
7934 41.8
14 rows selected.
i. column Alaise
ii. Table Alaise
i. Column Alaise :
------------------
ex:-
14 rows selected.
note: if alaise contains morethan one word then should be placed in " "
and AS is optional
-> Alaise name is given to next table name is called as Table Aalise
LOWER() :
---------
LOWER('NA
---------
naresh it
UPPER() :
---------
ex:-
UPPER('NA
---------
NARESH IT
INITCAP() :
-----------
ex:-
INITCAP('
---------
Naresh It
LENGTH() :
----------
14 rows selected.
ASCII() :
---------
ASCII('A')
----------
65
ASCII('A')
----------
97
CHR() :
-------
C
-
a
C
-
A
LPAD() :
--------
ex:-
LPAD('RAMA
----------
RAMA
RPAD() :
--------
RPAD('RAMA
----------
RAMA******
***RAMA***
LPAD(RPAD(
----------
***RAMA***
*****NARESH IT*****
LTRIM() :
---------
LTRI
----
RAMA
RTRIM() :
---------
RTR
---
RAM
TRIM() :
--------
ex:-
RTRI
----
RAMA
SACHIN TENDULKAR
RTRIM('
-------
SACHIN
SACHIN TENDULKAR
REPLACE() :
-----------
REPLACE('A
----------
ICICI BANK
TRANSLATE() :
-------------
TRANSL
------
*&&^%%
-- write a package program to find given employee DEPT. NAME & his grade
Package Spefication :
---------------------
Package Body :
--------------
End emp_pack;
/
calling programs :
------------------
*
ERROR at line 1:
ORA-20001: Employ record not found.
ORA-06512: at "ORA8PM.EMP_PACK", line 11
ORA-06512: at line 1
EMP_PACK.EMP_GRADE(7839)
-------------------------------------------------------------------------
------
7839 Employee Grade is 5
EMP_PACK.EMP_GRADE(7369)
-------------------------------------------------------------------------
------
7369 Employee Grade is 2
EMP_PACK.EMP_GRADE(9000)
-------------------------------------------------------------------------
------
Employ Record Not Found.
Function OverLoading :
----------------------
-> Function Name is same and it supports different data types or No.of
Parameters is called as Function Overloading
ex:-
Package body :
--------------
FO_PACK.ADD_VAL(100,200)
------------------------
300
FO_PACK.ADD_VAL(100,200,500)
----------------------------
800
FO_PACK.ADD_VAL('NARESH','IT')
------------------------------------------------------------------
naresh it
Package Specification :
-----------------------
temp_group_master
------------------
temp_value_version
-------------------
Table creation :
-----------------
Exceution :
-----------
OBJECT_NAME
-------------------------------------------------------------------------
---------------
MY_PACK
EMP_PACK
FO_PACK
P1
** to see the particular page body
TEXT
-------------------------------------------------------------------------
---------------------------
package emp_pack
is
Procedure emp_dname ( p_empno emp.empno%type );
Function emp_grade ( p_empno emp.empno%type) return Varchar2;
End emp_pack;
package body emp_pack
is
Procedure emp_dname ( p_empno emp.empno%type )
is
v_dname dept.dname%type;
Begin
select dname into v_dname from emp, dept where emp.deptno=dept.deptno
and empno = p_empno;
dbms_output.put_line( v_dname );
Exception
when no_data_found then
raise_application_error(-20001, 'Employ record not found.');
End emp_dname;
End emp_pack;
33 rows selected.
** Dropping packages
Table creation :
-----------------
SQL> UPDATE TG SET ISACTIVE= 0 WHERE EXISTS ( SELECT TEMPID FROM TV WHERE
TV.TEMPID=TG.TEMPID);
2 rows updated.
SQL> UPDATE TG SET ISACTIVE= 1 WHERE NOT EXISTS ( SELECT TEMPID FROM TV
WHERE TV.TEMPID=TG.TEMPID);
1 row updated.
or
SQL> UPDATE TG SET ISACTIVE= case when ( EXISTS ( SELECT 1 FROM TV WHERE
TV.TEMPID=TG.TEMPID and tg.itemid=tv.itemid)) then '0'
ELSE '1'
end;
Example Program :
-----------------
Validations :
-------------
Table Creation :
----------------
Bank_Mas :
----------
Bank_Trans :
------------
Sequences :
-----------
Acnos :
-------
Tnos :
------
PACKAGE SPECIFICATION :
-----------------------
Example Program :
-----------------
Validations :
-------------
Table Creation :
----------------
Bank_Mas :
----------
Bank_Trans :
------------
Sequences :
-----------
Acnos :
-------
Tnos :
------
PACKAGE SPECIFICATION :
-----------------------
End BANK_PACK;
/
PACKAGE BODY :
--------------
End min_stat;
Example Program :
-----------------
Validations :
-------------
Table Creation :
----------------
Bank_Mas :
----------
Bank_Trans :
------------
Create Table Bank_Trans( Tno number(10), sacno varchar2(10),
dacno varchar2(10), tdate date,
ttype char(1), tamt number(8,2)
);
Sequences :
-----------
Acnos :
-------
Tnos :
------
PACKAGE SPECIFICATION :
-----------------------
End BANK_PACK;
/
PACKAGE BODY :
--------------
END BANK_PACK;
/
SQL> COMMIT;
Commit complete.
Invalid input :
---------------
*
ERROR at line 1:
ORA-20002: Mobileno Already Registered.
ORA-06512: at "ORA8PM.BANK_PACK", line 19
ORA-06512: at line 1
*
ERROR at line 1:
ORA-20003: Invalid Accoun type....
ORA-06512: at "ORA8PM.BANK_PACK", line 22
ORA-06512: at line 1
*
ERROR at line 1:
ORA-20004: Min. A/c Opening Balance Rs.1000/-.
ORA-06512: at "ORA8PM.BANK_PACK", line 25
ORA-06512: at line 1
BANK_PACK.CHK_BAL('SBI1')
-------------------------
2000
BANK_PACK.CHK_BAL(9000994005)
-----------------------------
2000
****Account Statement****
sbi1 01-OCT-23 w 300
sbi1 06-OCT-23 w 500
sbi1 14-OCT-23 d 800
sbi1 20-OCT-23 w 300
sbi1 21-OCT-23 w 600
**************************
sample insertions :
-------------------
9 rows selected.
TRIGGERS :
----------
-> Trigger is one of the Named Block program and used to execute
automatically
Trigger Parts :
---------------
Trigger syntax :-
-----------------
** to perform any DML operations on SQL prompt first data will be stored
ROLLBACK segment
DEPT -- step3
-----
DEPTNO DNAME LOC
50 MATHS HYD
before insert
before update :NEW.
before delete
after insert
after insert
after delete :OLD.
after update
Example :-
DEPT -- step4
-----
DEPTNO DNAME LOC
50 MATHS hyd
Triger program :
----------------
Trigger created.
SQL> insert into dept values ( 50, 'maths', 'hyd' );
1 row created.
Example2 :-
Example Program :
-----------------
Validations :
-------------
Table Creation :
----------------
Bank_Mas :
----------
Bank_Trans :
------------
Sequences :
-----------
Acnos :
-------
Tnos :
------
PACKAGE SPECIFICATION :
-----------------------
End BANK_PACK;
/
PACKAGE BODY :
--------------
END BANK_PACK;
/
CALLING PACKAGE PROGRAMS :
--------------------------
SQL> COMMIT;
Commit complete.
Invalid input :
---------------
*
ERROR at line 1:
ORA-20002: Mobileno Already Registered.
ORA-06512: at "ORA8PM.BANK_PACK", line 19
ORA-06512: at line 1
*
ERROR at line 1:
ORA-20003: Invalid Accoun type....
ORA-06512: at "ORA8PM.BANK_PACK", line 22
ORA-06512: at line 1
*
ERROR at line 1:
ORA-20004: Min. A/c Opening Balance Rs.1000/-.
ORA-06512: at "ORA8PM.BANK_PACK", line 25
ORA-06512: at line 1
BANK_PACK.CHK_BAL('SBI1')
-------------------------
2000
BANK_PACK.CHK_BAL(9000994005)
-----------------------------
2000
****Account Statement****
sbi1 01-OCT-23 w 300
sbi1 06-OCT-23 w 500
sbi1 14-OCT-23 d 800
sbi1 20-OCT-23 w 300
sbi1 21-OCT-23 w 600
**************************
sample insertions :
-------------------
9 rows selected.
TRIGGERS :
----------
-> Trigger is one of the Named Block program and used to execute
automatically
Trigger Parts :
---------------
Trigger syntax :-
-----------------
** to perform any DML operations on SQL prompt first data will be stored
ROLLBACK segment
DEPT -- step3
-----
DEPTNO DNAME LOC
50 MATHS HYD
before insert
before update :NEW.
before delete
after insert
after insert
after delete :OLD.
after update
Example :-
DEPT -- step4
-----
DEPTNO DNAME LOC
50 MATHS hyd
Triger program :
----------------
Trigger created.
1 row created.
Example2 :-
rollback segment :
-----------------
:old.empno=7902, :old.ename='ford'... :old.sal = 4650,...
testing:-
*********
1 row updated.
13 rows selected.
example 3 :
-----------
** create a employee backup table with the same structure of EMP table
without data
Table created.
Trigger program :
-----------------
END;
/
ROLLBACK SEGMENT :-
-------------------
Testing :-
1 row deleted.
12 rows selected.
sequence :
----------
table creation:
---------------
Trigger :-
-----------
rollback segment :-
*******************
:new.eno=1, :new.ename='king'
Testing:-
no rows selected
1 row created.
1 row created.
ENO ENAME
------ ----------
1 king
2 scott
3 james
example 6:-
-----------
-> write a trigger program to peform DML operations on EMP table and
Transaction status should be
EMPLOYEE_STATUS table
Table creation :-
-----------------
Table created.
Trigger program :
----------------
end if;
End;
/
Example Program :
-----------------
Validations :
-------------
Table Creation :
----------------
Bank_Mas :
----------
Bank_Trans :
------------
Sequences :
-----------
Acnos :
-------
Tnos :
------
PACKAGE SPECIFICATION :
-----------------------
End BANK_PACK;
/
PACKAGE BODY :
--------------
END BANK_PACK;
/
SQL> COMMIT;
Commit complete.
SQL> SELECT * FROM BANK_MAS;
Invalid input :
---------------
*
ERROR at line 1:
ORA-20002: Mobileno Already Registered.
ORA-06512: at "ORA8PM.BANK_PACK", line 19
ORA-06512: at line 1
*
ERROR at line 1:
ORA-20003: Invalid Accoun type....
ORA-06512: at "ORA8PM.BANK_PACK", line 22
ORA-06512: at line 1
*
ERROR at line 1:
ORA-20004: Min. A/c Opening Balance Rs.1000/-.
ORA-06512: at "ORA8PM.BANK_PACK", line 25
ORA-06512: at line 1
BANK_PACK.CHK_BAL('SBI1')
-------------------------
2000
BANK_PACK.CHK_BAL(9000994005)
-----------------------------
2000
****Account Statement****
sbi1 01-OCT-23 w 300
sbi1 06-OCT-23 w 500
sbi1 14-OCT-23 d 800
sbi1 20-OCT-23 w 300
sbi1 21-OCT-23 w 600
**************************
9 rows selected.
TRIGGERS :
----------
-> Trigger is one of the Named Block program and used to execute
automatically
Trigger syntax :-
-----------------
** to perform any DML operations on SQL prompt first data will be stored
ROLLBACK segment
DEPT -- step3
-----
DEPTNO DNAME LOC
50 MATHS HYD
before insert
before update :NEW.
before delete
after insert
after insert
after delete :OLD.
after update
Example :-
DEPT -- step4
-----
DEPTNO DNAME LOC
50 MATHS hyd
Triger program :
----------------
Trigger created.
1 row created.
Example2 :-
rollback segment :
-----------------
:old.empno=7902, :old.ename='ford'... :old.sal = 4650,...
testing:-
*********
13 rows selected.
example 3 :
-----------
** create a employee backup table with the same structure of EMP table
without data
Table created.
Trigger program :
-----------------
END;
/
ROLLBACK SEGMENT :-
-------------------
Testing :-
1 row deleted.
12 rows selected.
sequence :
----------
table creation:
---------------
Trigger :-
-----------
rollback segment :-
*******************
:new.eno=1, :new.ename='king'
Testing:-
no rows selected
1 row created.
1 row created.
1 row created.
ENO ENAME
------ ----------
1 king
2 scott
3 james
example 6:-
-----------
-> write a trigger program to peform DML operations on EMP table and
Transaction status should be
EMPLOYEE_STATUS table
Table creation :-
-----------------
Table created.
Trigger program :
----------------
end if;
End;
/
-> In Statement Level triggers, Trigger Access specifiers( new & old )
not supported
ex:-
HDATE
---------
26-JAN-23
15-AUG-23
25-DEC-23
Trigger program :
-----------------
14 rows updated.
14 rows selected.
1
------
1
1
------
1
ex:-
ex:-
Ex:-
Table creations :
-----------------
note: on complex views DML operations are not allowed, to allow DML
operations then to write INSTEAD of triggers
Trigger :
---------
no rows selected
1 row created.
STD_ID SNAME
---------- ----------
s1 anand
-> To write Triggers on DDL commands that type of Triggers are called as
SCHEMA LEVEL TRIGGERS
Ex:-
testing :
---------
Trigger dropped.
Testing :-
***********
V. DB LEVEL Triggers :
----------------------
ex:-
-- write a trigger program to main user login details
Table creation :
----------------
Trigger on LOGIN :
------------------
testing:-
connect to user:
----------------
username: ora8pm
password: tiger
SYSDATE-LOGIN_TIME
-------------------------------------------------------------------------
--
+000000000 00:08:56.000000
SYSDATE-LOGIN_TIME
-------------------------------------------------------------------------
--
+000000000 00:09:09.000000
SUBSTR(SYSDATE-LOGIN_TIME,12,8)
--------------------------------
00:10:26
SQL> /
SUBSTR(SYSDATE-LOGIN_TIME,12,8)
--------------------------------
00:10:30
SQL> /
SUBSTR(SYSDATE-LOGIN_TIME,12,8)
--------------------------------
00:10:33
LOGOUT TRIGGER :
----------------
testing:-
connect to user:
----------------
username: ora8pm
password: tiger
note: SCHEMA LEVEL & DB LEVEL Triggers are written and executed by DBA
only
Example Program :
-----------------
Validations :
-------------
Table Creation :
----------------
Bank_Mas :
----------
Bank_Trans :
------------
Sequences :
-----------
Acnos :
-------
Tnos :
------
PACKAGE SPECIFICATION :
-----------------------
End BANK_PACK;
/
PACKAGE BODY :
--------------
Create or replace package Body BANK_PACK
is
SQL> COMMIT;
Commit complete.
Invalid input :
---------------
*
ERROR at line 1:
ORA-20002: Mobileno Already Registered.
ORA-06512: at "ORA8PM.BANK_PACK", line 19
ORA-06512: at line 1
*
ERROR at line 1:
ORA-20003: Invalid Accoun type....
ORA-06512: at "ORA8PM.BANK_PACK", line 22
ORA-06512: at line 1
SQL> EXEC BANK_PACK.NEW_ACC('SMITH', 'HYD', 9000994007, 'S', 500 );
BEGIN BANK_PACK.NEW_ACC('SMITH', 'HYD', 9000994007, 'S', 500 ); END;
*
ERROR at line 1:
ORA-20004: Min. A/c Opening Balance Rs.1000/-.
ORA-06512: at "ORA8PM.BANK_PACK", line 25
ORA-06512: at line 1
BANK_PACK.CHK_BAL('SBI1')
-------------------------
2000
BANK_PACK.CHK_BAL(9000994005)
-----------------------------
2000
****Account Statement****
sbi1 01-OCT-23 w 300
sbi1 06-OCT-23 w 500
sbi1 14-OCT-23 d 800
sbi1 20-OCT-23 w 300
sbi1 21-OCT-23 w 600
**************************
sample insertions :
-------------------
TRIGGERS :
----------
-> Trigger is one of the Named Block program and used to execute
automatically
Trigger Parts :
---------------
Trigger syntax :-
-----------------
** to perform any DML operations on SQL prompt first data will be stored
ROLLBACK segment
DEPT -- step3
-----
DEPTNO DNAME LOC
50 MATHS HYD
before insert
before update :NEW.
before delete
after insert
after insert
after delete :OLD.
after update
Example :-
Triger program :
----------------
Trigger created.
1 row created.
Example2 :-
testing:-
*********
1 row updated.
13 rows selected.
example 3 :
-----------
** create a employee backup table with the same structure of EMP table
without data
Trigger program :
-----------------
END;
/
ROLLBACK SEGMENT :-
-------------------
Testing :-
1 row deleted.
12 rows selected.
sequence :
----------
table creation:
---------------
Trigger :-
-----------
rollback segment :-
*******************
:new.eno=1, :new.ename='king'
Testing:-
no rows selected
1 row created.
1 row created.
ENO ENAME
------ ----------
1 king
2 scott
3 james
example 6:-
-----------
-> write a trigger program to peform DML operations on EMP table and
Transaction status should be
EMPLOYEE_STATUS table
Table creation :-
-----------------
Table created.
Trigger program :
----------------
end if;
End;
/
II. STATEMENT LEVEL TRIGGERS :
------------------------------
-> In Statement Level triggers, Trigger Access specifiers( new & old )
not supported
ex:-
HDATE
---------
26-JAN-23
15-AUG-23
25-DEC-23
Trigger program :
-----------------
14 rows updated.
14 rows selected.
** why we are usign TRUNCATE on SYSDATE
1
------
1
1
------
1
ex:-
ex:-
Ex:-
Table creations :
-----------------
note: on complex views DML operations are not allowed, to allow DML
operations then to write INSTEAD of triggers
Trigger :
---------
no rows selected
no rows selected
1 row created.
STD_ID SNAME
---------- ----------
s1 anand
-> To write Triggers on DDL commands that type of Triggers are called as
SCHEMA LEVEL TRIGGERS
Ex:-
testing :
---------
Trigger dropped.
Testing :-
***********
V. DB LEVEL Triggers :
----------------------
ex:-
Table creation :
----------------
Trigger on LOGIN :
------------------
testing:-
connect to user:
----------------
username: ora8pm
password: tiger
SYSDATE-LOGIN_TIME
-------------------------------------------------------------------------
--
+000000000 00:08:56.000000
SYSDATE-LOGIN_TIME
-------------------------------------------------------------------------
--
+000000000 00:09:09.000000
SUBSTR(SYSDATE-LOGIN_TIME,12,8)
--------------------------------
00:10:26
SQL> /
SUBSTR(SYSDATE-LOGIN_TIME,12,8)
--------------------------------
00:10:30
SQL> /
SUBSTR(SYSDATE-LOGIN_TIME,12,8)
--------------------------------
00:10:33
LOGOUT TRIGGER :
----------------
connect to user:
----------------
username: ora8pm
password: tiger
note: SCHEMA LEVEL & DB LEVEL Triggers are written and executed by DBA
only
OBJECT_NAME
-------------------------------------------------------------------------
--------
STD_COMP_VIEW_TRIG
EMP_DB_INS_TRIG
TRUNC_TRIG
LOGIN_TRIG
LOGOUT_TRIG
or
TRIGGER_NAME
------------------------------
EMP_DB_INS_TRIG
STD_COMP_VIEW_TRIG
LOGIN_TRIG
TRUNC_TRIG
LOGOUT_TRIG
TEXT
-------------------------------------------------------------------------
-------------------------
trigger emp_db_ins_trig
Before Insert on EMP_DB
for each row
begin
-- select my_seq.nextval into :new.eno from dual; ** before
oracle 11g version
8 rows selected.
** DROPPING TRIGGERS :
**********************
Validations :
-------------
Trigger Program :
-----------------
if bank_pack.chk_bal(:new.sacno) >
End;
/
Example Program :
-----------------
Validations :
-------------
Table Creation :
----------------
Bank_Mas :
----------
Bank_Trans :
------------
Acnos :
-------
PACKAGE SPECIFICATION :
-----------------------
End BANK_PACK;
/
PACKAGE BODY :
--------------
END BANK_PACK;
/
SQL> COMMIT;
Commit complete.
Invalid input :
---------------
*
ERROR at line 1:
ORA-20002: Mobileno Already Registered.
ORA-06512: at "ORA8PM.BANK_PACK", line 19
ORA-06512: at line 1
*
ERROR at line 1:
ORA-20003: Invalid Accoun type....
ORA-06512: at "ORA8PM.BANK_PACK", line 22
ORA-06512: at line 1
*
ERROR at line 1:
ORA-20004: Min. A/c Opening Balance Rs.1000/-.
ORA-06512: at "ORA8PM.BANK_PACK", line 25
ORA-06512: at line 1
BANK_PACK.CHK_BAL('SBI1')
-------------------------
2000
BANK_PACK.CHK_BAL(9000994005)
-----------------------------
2000
VI. MINI STATEMENT :
--------------------
****Account Statement****
sbi1 01-OCT-23 w 300
sbi1 06-OCT-23 w 500
sbi1 14-OCT-23 d 800
sbi1 20-OCT-23 w 300
sbi1 21-OCT-23 w 600
**************************
sample insertions :
-------------------
9 rows selected.
TRIGGERS :
----------
-> Trigger is one of the Named Block program and used to execute
automatically
Trigger Parts :
---------------
Trigger syntax :-
-----------------
** to perform any DML operations on SQL prompt first data will be stored
ROLLBACK segment
DEPT -- step3
-----
DEPTNO DNAME LOC
50 MATHS HYD
before insert
before update :NEW.
before delete
after insert
after insert
after delete :OLD.
after update
Example :-
DEPT -- step4
-----
DEPTNO DNAME LOC
50 MATHS hyd
Triger program :
----------------
Trigger created.
1 row created.
Example2 :-
-- Write a trigger program to raise error if updating salary is
lessthan existing salary
rollback segment :
-----------------
:old.empno=7902, :old.ename='ford'... :old.sal = 4650,...
testing:-
*********
1 row updated.
13 rows selected.
example 3 :
-----------
** create a employee backup table with the same structure of EMP table
without data
Table created.
Trigger program :
-----------------
END;
/
ROLLBACK SEGMENT :-
-------------------
Testing :-
1 row deleted.
12 rows selected.
sequence :
----------
table creation:
---------------
Trigger :-
-----------
:new.eno=1, :new.ename='king'
Testing:-
no rows selected
1 row created.
1 row created.
1 row created.
ENO ENAME
------ ----------
1 king
2 scott
3 james
example 6:-
-----------
-> write a trigger program to peform DML operations on EMP table and
Transaction status should be
EMPLOYEE_STATUS table
Table creation :-
-----------------
Table created.
Trigger program :
----------------
end if;
End;
/
-> In Statement Level triggers, Trigger Access specifiers( new & old )
not supported
ex:-
HDATE
---------
26-JAN-23
15-AUG-23
25-DEC-23
Trigger program :
-----------------
14 rows updated.
14 rows selected.
1
------
1
1
------
1
ex:-
ex:-
Ex:-
Table creations :
-----------------
note: on complex views DML operations are not allowed, to allow DML
operations then to write INSTEAD of triggers
Trigger :
---------
no rows selected
no rows selected
1 row created.
STD_ID SNAME
---------- ----------
s1 anand
-> To write Triggers on DDL commands that type of Triggers are called as
SCHEMA LEVEL TRIGGERS
Ex:-
testing :
---------
Trigger dropped.
Testing :-
***********
V. DB LEVEL Triggers :
----------------------
ex:-
Table creation :
----------------
Trigger on LOGIN :
------------------
Create or replace trigger login_trig
AFTER LOGON ON SCHEMA
Begin
Insert into login_details values ( tid_seq.nextval, uid, user, sysdate,
null, null );
End;
/
testing:-
connect to user:
----------------
username: ora8pm
password: tiger
SYSDATE-LOGIN_TIME
-------------------------------------------------------------------------
--
+000000000 00:08:56.000000
SYSDATE-LOGIN_TIME
-------------------------------------------------------------------------
--
+000000000 00:09:09.000000
SUBSTR(SYSDATE-LOGIN_TIME,12,8)
--------------------------------
00:10:26
SQL> /
SUBSTR(SYSDATE-LOGIN_TIME,12,8)
--------------------------------
00:10:30
SQL> /
SUBSTR(SYSDATE-LOGIN_TIME,12,8)
--------------------------------
00:10:33
LOGOUT TRIGGER :
----------------
testing:-
connect to user:
----------------
username: ora8pm
password: tiger
note: SCHEMA LEVEL & DB LEVEL Triggers are written and executed by DBA
only
** All created trigger names are stored in USER_TRIGGERS/USER_OBJECTS
OBJECT_NAME
-------------------------------------------------------------------------
--------
STD_COMP_VIEW_TRIG
EMP_DB_INS_TRIG
TRUNC_TRIG
LOGIN_TRIG
LOGOUT_TRIG
or
TRIGGER_NAME
------------------------------
EMP_DB_INS_TRIG
STD_COMP_VIEW_TRIG
LOGIN_TRIG
TRUNC_TRIG
LOGOUT_TRIG
TEXT
-------------------------------------------------------------------------
-------------------------
trigger emp_db_ins_trig
Before Insert on EMP_DB
for each row
begin
-- select my_seq.nextval into :new.eno from dual; ** before
oracle 11g version
8 rows selected.
** DROPPING TRIGGERS :
**********************
Validations :
-------------
Trigger Program :
-----------------
if :new.ttype='d' then
Bank_Pack.credit( :new.sacno, :new.tamt ); -- credit
procedure is calling
elsif :new.ttype='w' then
Testing :
---------
SQL>
SQL> insert into bank_trans(sacno, ttype, tamt ) values ( 'sbi1', 'd',
1000 );
amt. deposited.
1 row created.
Example Program :
-----------------
Validations :
-------------
Table Creation :
----------------
Bank_Mas :
----------
Bank_Trans :
------------
Sequences :
-----------
Acnos :
-------
PACKAGE SPECIFICATION :
-----------------------
End BANK_PACK;
/
PACKAGE BODY :
--------------
END BANK_PACK;
/
SQL> COMMIT;
Commit complete.
SQL> SELECT * FROM BANK_MAS;
Invalid input :
---------------
*
ERROR at line 1:
ORA-20002: Mobileno Already Registered.
ORA-06512: at "ORA8PM.BANK_PACK", line 19
ORA-06512: at line 1
*
ERROR at line 1:
ORA-20003: Invalid Accoun type....
ORA-06512: at "ORA8PM.BANK_PACK", line 22
ORA-06512: at line 1
*
ERROR at line 1:
ORA-20004: Min. A/c Opening Balance Rs.1000/-.
ORA-06512: at "ORA8PM.BANK_PACK", line 25
ORA-06512: at line 1
BANK_PACK.CHK_BAL('SBI1')
-------------------------
2000
BANK_PACK.CHK_BAL(9000994005)
-----------------------------
2000
****Account Statement****
sbi1 01-OCT-23 w 300
sbi1 06-OCT-23 w 500
sbi1 14-OCT-23 d 800
sbi1 20-OCT-23 w 300
sbi1 21-OCT-23 w 600
**************************
9 rows selected.
TRIGGERS :
----------
-> Trigger is one of the Named Block program and used to execute
automatically
Trigger syntax :-
-----------------
** to perform any DML operations on SQL prompt first data will be stored
ROLLBACK segment
DEPT -- step3
-----
DEPTNO DNAME LOC
50 MATHS HYD
before insert
before update :NEW.
before delete
after insert
after insert
after delete :OLD.
after update
Example :-
DEPT -- step4
-----
DEPTNO DNAME LOC
50 MATHS hyd
Triger program :
----------------
Trigger created.
1 row created.
Example2 :-
rollback segment :
-----------------
:old.empno=7902, :old.ename='ford'... :old.sal = 4650,...
testing:-
*********
13 rows selected.
example 3 :
-----------
** create a employee backup table with the same structure of EMP table
without data
Table created.
Trigger program :
-----------------
END;
/
ROLLBACK SEGMENT :-
-------------------
Testing :-
1 row deleted.
12 rows selected.
sequence :
----------
table creation:
---------------
Trigger :-
-----------
rollback segment :-
*******************
:new.eno=1, :new.ename='king'
Testing:-
no rows selected
1 row created.
1 row created.
1 row created.
ENO ENAME
------ ----------
1 king
2 scott
3 james
example 6:-
-----------
-> write a trigger program to peform DML operations on EMP table and
Transaction status should be
EMPLOYEE_STATUS table
Table creation :-
-----------------
Table created.
Trigger program :
----------------
end if;
End;
/
-> In Statement Level triggers, Trigger Access specifiers( new & old )
not supported
ex:-
HDATE
---------
26-JAN-23
15-AUG-23
25-DEC-23
Trigger program :
-----------------
14 rows updated.
14 rows selected.
1
------
1
1
------
1
ex:-
ex:-
Ex:-
Table creations :
-----------------
note: on complex views DML operations are not allowed, to allow DML
operations then to write INSTEAD of triggers
Trigger :
---------
no rows selected
1 row created.
STD_ID SNAME
---------- ----------
s1 anand
-> To write Triggers on DDL commands that type of Triggers are called as
SCHEMA LEVEL TRIGGERS
Ex:-
testing :
---------
Trigger dropped.
Testing :-
***********
V. DB LEVEL Triggers :
----------------------
ex:-
-- write a trigger program to main user login details
Table creation :
----------------
Trigger on LOGIN :
------------------
testing:-
connect to user:
----------------
username: ora8pm
password: tiger
SYSDATE-LOGIN_TIME
-------------------------------------------------------------------------
--
+000000000 00:08:56.000000
SYSDATE-LOGIN_TIME
-------------------------------------------------------------------------
--
+000000000 00:09:09.000000
SUBSTR(SYSDATE-LOGIN_TIME,12,8)
--------------------------------
00:10:26
SQL> /
SUBSTR(SYSDATE-LOGIN_TIME,12,8)
--------------------------------
00:10:30
SQL> /
SUBSTR(SYSDATE-LOGIN_TIME,12,8)
--------------------------------
00:10:33
LOGOUT TRIGGER :
----------------
testing:-
connect to user:
----------------
username: ora8pm
password: tiger
note: SCHEMA LEVEL & DB LEVEL Triggers are written and executed by DBA
only
OBJECT_NAME
-------------------------------------------------------------------------
--------
STD_COMP_VIEW_TRIG
EMP_DB_INS_TRIG
TRUNC_TRIG
LOGIN_TRIG
LOGOUT_TRIG
or
TRIGGER_NAME
------------------------------
EMP_DB_INS_TRIG
STD_COMP_VIEW_TRIG
LOGIN_TRIG
TRUNC_TRIG
LOGOUT_TRIG
TEXT
-------------------------------------------------------------------------
-------------------------
trigger emp_db_ins_trig
Before Insert on EMP_DB
for each row
begin
-- select my_seq.nextval into :new.eno from dual; ** before
oracle 11g version
8 rows selected.
** DROPPING TRIGGERS :
**********************
Validations :
-------------
Trigger Program :
-----------------
if :new.ttype='d' then
Bank_Pack.credit( :new.sacno, :new.tamt ); -- credit
procedure is calling
elsif :new.ttype='w' then
Testing :
---------
DEPOSIT AMT :
*************
1 row created.
Withdraw amount :
*****************
SQL> insert into bank_trans( sacno, ttype, tamt ) values ( 'sbi1', 'w',
600 );
amt. withdraw successfully
1 row created.
Amt.Transfer :
--------------
SQL> insert into bank_trans( sacno, dacno, ttype, tamt ) values ( 'sbi1',
'sbi2', 'at', 1500 );
amt. withdraw successfully
amt. deposited.
Amt. Transfer successfully.
1 row created.
INVALID INPUT :
***************
Invalid ttype :
---------------
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
COMPOSITE DATATYPES :
---------------------
ARRAY ->
x[1] = 10;
x[2] = 20;
x[3] = 30;
.
.
x[10]= 100;
x number;
x=100;
x=200;
N[1]=SMITH
N[2]=ALLEN
N[]
.
.
N[14]=MILLER
P[1]=900
P[2]=1700
P[]
.
.
P[14]=1400
DECLARE
TYPE NAMES IS TABLE OF EMP.ENAME%TYPE INDEX BY BINARY_INTEGER;
TYPE PAYS IS TABLE OF EMP.SAL%TYPE INDEX BY BINARY_INTEGER;
N NAMES;
P PAYS;
CNT NUMBER := 1;
BEGIN
-- FILLING N,P ARRAY ELEMENTS
SMITH............900
ALLEN............1700
WARD............1350
JONES............3075
MARTIN............1350
BLAKE............2950
CLARK............2550
HEMANTH............3100
KING............5100
TURNER............1600
ADAMS............1200
JAMES............1050
FORD............3100
MILLER............1400
i.ename=ALLEN
i.sal=1700
Package specification :
***********************
Package created.
Procedure :
-----------
calling procedure :
-------------------
declare
v_jobs job_pack.jobs_type;
Begin
emp_jobs(&deptno, v_jobs); -- calling procedure and v_jobs
contains given deptno. jobs
for i in v_jobs.first..v_jobs.last -- 1..3
loop
dbms_output.put_line( v_jobs(i ) );
end loop;
end;
/
MANAGER
PRESIDENT
CLERK
SQL> /
Enter value for deptno: 30
SALESMAN
SALESMAN
SALESMAN
MANAGER
SALESMAN
CLERK
14 rows selected.
LEAD :
*******
14 rows selected.
14 rows selected.
30 7900 JAMES CLERK 1050 1350
30 7654 MARTIN SALESMAN 1350 1350
30 7521 WARD SALESMAN 1350 1600
30 7844 TURNER SALESMAN 1600 1700
30 7499 ALLEN SALESMAN 1700 2950
30 7698 BLAKE MANAGER 2950 0
14 rows selected.
14 rows selected.
SQL> select empno, sal, dense_rank() over( order by sal desc ) as drnk
from emp;
14 rows selected.
PARTITIONS
Partitioning Methods
- Range partitioning
- List partitioning
Range Partitioning
SQL>
Create table emp345
(empno number(3) primary key,
ename varchar2(30),
sal number(8,2),
deptno number(2))
Partition by range (deptno)
(Partition p1 values less than (10),
Partition p2 values less than (20),
Partition p3 values less than (30),
Partition p4 values less than (40)
) ;
EMPNO
----------
22
11
44
33
List Partitioning
Use list partitioning when you require explicit control over how rows map
to partitions. You can specify a list of discrete values for the
partitioning column in the description for each partition.
Truncating Partitions
alter table emp345 truncate partition p5;
Merging Partitions
LOCKS
Lock means : U can do the update transaction at one location and the
another person do the same transaction at another location it can occurs
the dead lock situation.
1. Implicit Locks:
? U & another person do the same transaction at the same time dead
locks occurs at that time who enter the Transaction first that will
decided by the implicit Locks. Whose person can open the table that
person will do that transaction.
2. Explicit Locks:
Type of locks
note: another user cannot manipulate comm&sal of 7788,for the rest of the
numbers & entities he can do manipulation
Note: another user cannot manipulate comm&sal all the numbers, for the
rest of the entities he can do manipulation
note: another user cannot manipulate all the entities of the table
SQL * LOADER :
--------------
-> SQL *LOADER is used to copies Flat Files information to Oracle DBs
-- Example for copying NOTEPAD file data into Oracle Database Tables
notepad :
----------
1,king,5000,10
2,scott,6000,20
3,jones,4000,10
4,smith,4500,30
5,james,2500,20
6,allen,1800,10
.
.
100000,.....
Step1 :
-------
D:\EMP.TXT
-----------
1,king,5000,10
2,scott,6000,20
3,jones,4000,10
4,smith,4500,30
5,james,2500,20
6,allen,1800,10
Step2 :
--------
-- Connect to Ora8pm user and create a new table with 4 columns like
empno, ename, sal & deptno
username: ora8pm
password: tiger
Table created.
step 3:
-------
'D:\MYCTL.CTL'
--------------
LOAD DATA
INFILE "D:\EMP.TXT"
INSERT INTO TABLE EMP_DB
FIELDS TERMINATED BY ','
(EMPNO, ENAME,SAL,DEPTNO)
Step 4:
--------
control = d:\myctl.ctl
Copyright (c) 1982, 2009, Oracle and/or its affiliates. All rights
reserved.
step5 :
--------
6 rows selected.
Example for copying EXCEL SHEET file data into Oracle Database Tables:
**********************************************************************
Step1 :
-------
D:\EMP.CSV
-----------
1,king,5000,10
2,scott,6000,20
3,jones,4000,10
4,smith,4500,30
5,james,2500,20
6,allen,1800,10
Step2 :
--------
-- Connect to Ora8pm user and create a new table with 4 columns like
empno, ename, sal & deptno
username: ora8pm
password: tiger
Table created.
step 3:
-------
'D:\MYCTL.CTL'
--------------
LOAD DATA
INFILE "D:\EMP.CSV"
INSERT INTO TABLE EMP_DB
FIELDS TERMINATED BY ','
(EMPNO, ENAME,SAL,DEPTNO)
Step 4:
--------
control = d:\myctl.ctl
Copyright (c) 1982, 2009, Oracle and/or its affiliates. All rights
reserved.
6 rows selected.
Step1 :
-------
D:\EMP.txt
-----------
7,blake,6000,30
8,clark,3000,10
9,ford,4000,10
step 2:
-------
'D:\MYCTL.CTL'
--------------
LOAD DATA
INFILE "D:\EMP.CSV"
APPEND INTO TABLE EMP_DB
FIELDS TERMINATED BY ','
(EMPNO, ENAME,SAL,DEPTNO)
Step 4:
--------
-- Execute the script
control = d:\myctl.ctl
Copyright (c) 1982, 2009, Oracle and/or its affiliates. All rights
reserved.
step5 :
--------
6 rows selected.
-> EXPORT & IMPORTS are copying data from source database to
destination database
EXPORT :
--------
EX:-
C:\Users\sarmamicrosoft>exp
Export: Release 11.2.0.2.0 - Production on Fri Nov 10 20:12:52 2023
Copyright (c) 1982, 2009, Oracle and/or its affiliates. All rights
reserved.
Username: ora8pm/tiger
C:\Users\sarmamicrosoft>
step2 :
-------
connect :
---------
username : system
password : server
User created.
Grant succeeded.
step 3:
-------
IMPORT :
--------
C:\Users\sarmamicrosoft>IMP
Copyright (c) 1982, 2009, Oracle and/or its affiliates. All rights
reserved.
Username: client_user/tiger
C:\Users\sarmamicrosoft>
Step 4:
-------
ex:-
SQL> SELECT OBJECT_NAME FROM USER_OBJECTS;
Example Program :
-----------------
Validations :
-------------
Table Creation :
----------------
Bank_Mas :
----------
Bank_Trans :
------------
Sequences :
-----------
Acnos :
-------
PACKAGE SPECIFICATION :
-----------------------
End BANK_PACK;
/
PACKAGE BODY :
--------------
END BANK_PACK;
/
SQL> COMMIT;
Commit complete.
Invalid input :
---------------
*
ERROR at line 1:
ORA-20002: Mobileno Already Registered.
ORA-06512: at "ORA8PM.BANK_PACK", line 19
ORA-06512: at line 1
*
ERROR at line 1:
ORA-20003: Invalid Accoun type....
ORA-06512: at "ORA8PM.BANK_PACK", line 22
ORA-06512: at line 1
*
ERROR at line 1:
ORA-20004: Min. A/c Opening Balance Rs.1000/-.
ORA-06512: at "ORA8PM.BANK_PACK", line 25
ORA-06512: at line 1
BANK_PACK.CHK_BAL('SBI1')
-------------------------
2000
BANK_PACK.CHK_BAL(9000994005)
-----------------------------
2000
****Account Statement****
sbi1 01-OCT-23 w 300
sbi1 06-OCT-23 w 500
sbi1 14-OCT-23 d 800
sbi1 20-OCT-23 w 300
sbi1 21-OCT-23 w 600
**************************
sample insertions :
-------------------
insert into bank_trans values ( 1, 'sbi1', null, '16-sep-2023', 'd', 1000
);
insert into bank_trans values ( 2, 'sbi1', null, '23-sep-2023', 'w', 200
);
insert into bank_trans values ( 4, 'sbi2', null, '29-sep-2023', 'd', 500
);
insert into bank_trans values ( 5, 'sbi1', null, '01-oct-2023', 'w', 300
);
insert into bank_trans values ( 6, 'sbi1', null, '06-oct-2023', 'w', 500
);
insert into bank_trans values ( 7, 'sbi2', null, '09-oct-2023', 'w', 100
);
insert into bank_trans values ( 8, 'sbi1', null, '14-oct-2023', 'd', 800
);
insert into bank_trans values ( 9, 'sbi1', null, '20-oct-2023', 'w', 300
);
insert into bank_trans values ( 10, 'sbi1', null, '21-oct-2023', 'w', 600
);
9 rows selected.
TRIGGERS :
----------
-> Trigger is one of the Named Block program and used to execute
automatically
Trigger Parts :
---------------
Trigger syntax :-
-----------------
** to perform any DML operations on SQL prompt first data will be stored
ROLLBACK segment
DEPT -- step3
-----
DEPTNO DNAME LOC
50 MATHS HYD
before insert
before update :NEW.
before delete
after insert
after insert
after delete :OLD.
after update
Example :-
DEPT -- step4
-----
DEPTNO DNAME LOC
50 MATHS hyd
Triger program :
----------------
1 row created.
Example2 :-
rollback segment :
-----------------
:old.empno=7902, :old.ename='ford'... :old.sal = 4650,...
testing:-
*********
1 row updated.
13 rows selected.
example 3 :
-----------
** create a employee backup table with the same structure of EMP table
without data
Table created.
Trigger program :
-----------------
END;
/
ROLLBACK SEGMENT :-
-------------------
Testing :-
1 row deleted.
12 rows selected.
sequence :
----------
table creation:
---------------
create table emp_db( eno number(2), ename varchar2(10));
Trigger :-
-----------
rollback segment :-
*******************
:new.eno=1, :new.ename='king'
Testing:-
no rows selected
1 row created.
1 row created.
1 row created.
ENO ENAME
------ ----------
1 king
2 scott
3 james
example 6:-
-----------
-> write a trigger program to peform DML operations on EMP table and
Transaction status should be
EMPLOYEE_STATUS table
Table creation :-
-----------------
SQL> Create table emp_status ( eno number(4), sdate date, status
varchar2(40));
Table created.
Trigger program :
----------------
end if;
End;
/
-> In Statement Level triggers, Trigger Access specifiers( new & old )
not supported
ex:-
HDATE
---------
26-JAN-23
15-AUG-23
25-DEC-23
Trigger program :
-----------------
14 rows updated.
14 rows selected.
1
------
1
1
------
1
ex:-
ex:-
Ex:-
Table creations :
-----------------
note: on complex views DML operations are not allowed, to allow DML
operations then to write INSTEAD of triggers
Trigger :
---------
no rows selected
1 row created.
STD_ID SNAME
---------- ----------
s1 anand
-> To write Triggers on DDL commands that type of Triggers are called as
SCHEMA LEVEL TRIGGERS
Ex:-
testing :
---------
Trigger dropped.
Testing :-
***********
V. DB LEVEL Triggers :
----------------------
ex:-
Table creation :
----------------
Trigger on LOGIN :
------------------
testing:-
connect to user:
----------------
username: ora8pm
password: tiger
SYSDATE-LOGIN_TIME
-------------------------------------------------------------------------
--
+000000000 00:08:56.000000
SYSDATE-LOGIN_TIME
-------------------------------------------------------------------------
--
+000000000 00:09:09.000000
SQL> select substr( sysdate - login_time,12,8 ) from login_details where
tid=1;
SUBSTR(SYSDATE-LOGIN_TIME,12,8)
--------------------------------
00:10:26
SQL> /
SUBSTR(SYSDATE-LOGIN_TIME,12,8)
--------------------------------
00:10:30
SQL> /
SUBSTR(SYSDATE-LOGIN_TIME,12,8)
--------------------------------
00:10:33
LOGOUT TRIGGER :
----------------
testing:-
connect to user:
----------------
username: ora8pm
password: tiger
note: SCHEMA LEVEL & DB LEVEL Triggers are written and executed by DBA
only
OBJECT_NAME
-------------------------------------------------------------------------
--------
STD_COMP_VIEW_TRIG
EMP_DB_INS_TRIG
TRUNC_TRIG
LOGIN_TRIG
LOGOUT_TRIG
or
TRIGGER_NAME
------------------------------
EMP_DB_INS_TRIG
STD_COMP_VIEW_TRIG
LOGIN_TRIG
TRUNC_TRIG
LOGOUT_TRIG
TEXT
-------------------------------------------------------------------------
-------------------------
trigger emp_db_ins_trig
Before Insert on EMP_DB
for each row
begin
-- select my_seq.nextval into :new.eno from dual; ** before
oracle 11g version
:new.eno := my_seq.nextval; -- oracle 11g feature
end;
8 rows selected.
** DROPPING TRIGGERS :
**********************
Validations :
-------------
Trigger Program :
-----------------
Testing :
---------
DEPOSIT AMT :
*************
1 row created.
Withdraw amount :
*****************
SQL> insert into bank_trans( sacno, ttype, tamt ) values ( 'sbi1', 'w',
600 );
amt. withdraw successfully
1 row created.
Amt.Transfer :
--------------
SQL> insert into bank_trans( sacno, dacno, ttype, tamt ) values ( 'sbi1',
'sbi2', 'at', 1500 );
amt. withdraw successfully
amt. deposited.
Amt. Transfer successfully.
1 row created.
Invalid ttype :
---------------
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
9 rows selected.
COMPOSITE DATATYPES :
---------------------
ARRAY ->
x[1] = 10;
x[2] = 20;
x[3] = 30;
.
.
x[10]= 100;
x number;
x=100;
x=200;
N[1]=SMITH
N[2]=ALLEN
N[]
.
.
N[14]=MILLER
P[1]=900
P[2]=1700
P[]
.
.
P[14]=1400
DECLARE
TYPE NAMES IS TABLE OF EMP.ENAME%TYPE INDEX BY BINARY_INTEGER;
TYPE PAYS IS TABLE OF EMP.SAL%TYPE INDEX BY BINARY_INTEGER;
N NAMES;
P PAYS;
CNT NUMBER := 1;
BEGIN
-- FILLING N,P ARRAY ELEMENTS
FOR I IN ( SELECT ENAME, SAL FROM EMP )
LOOP
N(CNT) := I.ENAME;
P(CNT) := I.SAL;
CNT := CNT + 1; -- 3
END LOOP;
SMITH............900
ALLEN............1700
WARD............1350
JONES............3075
MARTIN............1350
BLAKE............2950
CLARK............2550
HEMANTH............3100
KING............5100
TURNER............1600
ADAMS............1200
JAMES............1050
FORD............3100
MILLER............1400
EXAMPLE:
--------
DECLARE
TYPE NAMES IS TABLE OF EMP.ENAME%TYPE INDEX BY BINARY_INTEGER;
TYPE PAYS IS TABLE OF EMP.SAL%TYPE INDEX BY BINARY_INTEGER;
N NAMES;
P PAYS;
CNT NUMBER := 1;
BEGIN
-- FILLING N,P ARRAY ELEMENTS
Declare
type emp_type is table of emp%rowtype index by Binary_Integer;
e emp_type;
cnt number := 1;
Begin
NAMED BLOCKS :
--------------
-> Named Block programs are stored in DB permanently
-> All Named Block Programs are start with CREATE statement
SUB-PROGRAMS :
--------------
i. stored procedures
i. Stored Procedures :
----------------------
-> While calling the stored procedures we can pass parameters and
maximum 32 parameters are supported
I. RE-USABILITY :
II. MODULARITY :
adv.
* easy to understand
-> All created stored procedure names are stored in USER_OBJECTS table
( pre-defined table )
-> All stored procedure Bodies are stored in USER_SOURCE table ( pre-
defined table )
syn:-
Ex:-
on sql prompt :
***************
ex:-
syn:-
begin
<procedure_name>;
End;
/
ex:-
Begin
my_proc;
End;
/
Welcome to Stored Procedures...
Procedure created.
Procedure created.
note:
ex:-
6 rows selected.
7 rows selected.
LINE/COL ERROR
-------- ----------------------------------------------------------------
-
12/5 PLS-00113: END identifier 'EMP_INCR' must match 'EMP_INCR_PROC'
at line 1, column 11
Procedure :
-----------
14 rows selected.
14 rows selected.
14 rows selected.
i. IN
ii. OUT
iii. IN OUT
i. IN :
-------
Procedure created.
LINE/COL ERROR
-------- ----------------------------------------------------------------
-
4/8 PL/SQL: Statement ignored
4/8 PLS-00363: expression 'X' cannot be used as an assignment target
ii. OUT :
---------
ex:-
-- write a stored procedure to find sum of two given numbers and return
the output
Calling procedure :
-------------------
ON SQL Prompt :
***************
RES
------
600
SQL> declare
result number;
begin
add_proc(500, 400 , result );
dbms_output.put_line( 'sum of two given numbers = '||result);
end;
/
sum of two given numbers = 900
EX:-
calling procedure :
*******************
declare
v_netsal Number;
Begin
emp_netsal_Proc( &empno, v_netsal); -- calling procedure
dbms_output.put_line('Given Employ Net Sal Rs.'||v_netsal);
End;
/
SQL> /
Enter value for empno: 7521
Given Employ Net Sal Rs.2375
Ex:-
calling procedure :
-------------------
declare
v_grade number;
begin
emp_grade( &empno, v_grade );
dbms_output.put_line( 'Emp Grade is ' || v_grade );
end;
/
SQL> /
Enter value for empno: 7369
Emp Grade is 1
Ex:-
generating aadharnos:
---------------------
14 rows updated.
14 rows selected.
Stored Procedure :
******************
Declare
v_cid customer_db.cid%type;
v_cust_name customer_db.cust_name%type;
v_cust_desig customer_db.cust_desig%type;
v_cust_db customer_db.cust_db%type;
Begin
get_info( &aadharno, v_cid, v_cust_name, v_cust_desig, v_cust_db);
-- calling procedure
dbms_output.put_line( v_cid );
dbms_output.put_line( v_cust_name );
dbms_output.put_line( v_cust_desig );
dbms_output.put_line( v_cust_db );
End;
/
Validations :
-------------
step1 :
Table creation :
----------------
step2 :
-------
Step3 :
-------
Calling procedure :
-------------------
Declare
v_status varchar2(100);
Begin
User_Registration_Proc( &cid, &accno, &username, &password,
&cnf_password, &created_by, v_status );
dbms_output.put_line( v_status );
End;
/
SQL> /
Enter value for cid: 12
Enter value for accno: 'sbi2'
Enter value for username: 'sbi_kris'
Enter value for password: 'kris@786'
Enter value for cnf_password: 'kris@786'
Enter value for created_by: 'customer'
User Created Successfully...
INVALID INPUTS :
-----------------
Declare
v_status varchar2(100);
Begin
User_Registration_Proc( &cid, &accno, &username, &password,
&cnf_password, &created_by, v_status );
dbms_output.put_line( v_status );
End;
/
SQL> /
Enter value for cid: 13
Enter value for accno: 'sbi3'
Enter value for username: 'scott_sbi'
Enter value for password: 'king@123'
Enter value for cnf_password: '123@king'
Enter value for created_by: 'admin'
Enter Password and Cnf. Passwords should be same..
SQL> /
Enter value for cid: 13
Enter value for accno: 'sbi4'
Enter value for username: 'king_sbi'
Enter value for password: 'king@123'
Enter value for cnf_password: 'king@123'
Enter value for created_by: 'admin'
UserName already Exists.....
SQL> /
Enter value for cid: 13
Enter value for accno: 'sbi3'
Enter value for username: 'scott_sbi'
Enter value for password: 'scott'
Enter value for cnf_password: 'scott'
Enter value for created_by: 'admin'
Min. Length of Password is 6 chars.
calling Procedure :
-------------------
Declare
v_status varchar2(100);
Begin
login_proc( &user_name, &password, v_status ); -- calling Procedure
dbms_output.put_line( v_status );
End;
/
SQL> /
Enter value for user_name: 'king_sbi'
Enter value for password: 'king'
Invalid UserName/Password
iii. IN OUT :
-------------
ex:-
calling Procedure :
*******************
declare
res number(10) := &res; -- 10
Begin
Inout_proc( res );
dbms_output.put_line( 'Result = ' || res );
end;
/
-> While calling the stored procedures if we are not passing value to
Parameters then by default
specified default values are taken.
ex:-
calling procedure :
*******************
Note: In abvoe 2nd example, Dept.Name taken as 'HYD' and LOC taken as
'Unknown', because by default procedures calling according to
positions.
NOTATIONS :
-----------
I. POSITIONAL NOTATIONS
I. POSITIONAL NOTATIONS :
-------------------------
ex:-
ex:-
6 rows selected.
ex:-
7 rows selected.
OBJECT_NAME
-------------------------------------------------------------------------
-------------
INOUT_PROC
EMP_NETSAL_PROC
EMP_GRADE
GET_INFO
USER_REGISTRATION_PROC
LOGIN_PROC
ADD_PROC
MY_PROC
DEPT_INS
EMP_INCR_PROC
EMP_DEL
EMP_BONUS_PROC
DEPT_INS_PROC
13 rows selected.
TEXT
-------------------------------------------------------------------------
---------------------------
procedure User_Registration_Proc( p_cid IN number,
p_accno IN varchar2,
p_user_name IN
varchar2, -- king_sbi
p_password IN
varchar2, -- king@123
p_cnf_password IN
varchar2,
p_created_by IN
varchar2,
p_status Out Varchar2
)
Is
Cnt Number;
Begin
Select count(*) Into cnt from bank_user_reg where user_name =
p_user_Name; -- if cnt=1 is exis
ts, cnt=0 not exists
if cnt=1 then
p_status := 'UserName already Exists.....';
elsif ASCII( substr( p_password ,1,1) ) Not Between 65 and 90 and
ASCII( substr( p_password ,1,1) ) Not Between 97 and 122 then
p_status := 'Password should be start with an Alphabet..';
elsif length(p_password) <6 then
p_status := 'Min. Length of Password is 6 chars.';
elsif p_password != p_cnf_password then
p_status := 'Enter Password and Cnf. Passwords should be same..';
elsif p_created_by not in ( 'admin','customer') then
p_status := 'Invalid Role...';
else
Insert into bank_user_reg values( tno_seq.nextval, p_cid, p_accno,
p_user_name , p_password, s
ysdate, p_created_by, 1);
28 rows selected.
** Dropping Procedures :
*************************
i. Modularity
ii. Re-usability
-> All created User Defined function Names are stored in USER_OBJECTS
-> All created User Defined Function Bodies are stored in USER_SOURCE
tables
Function Syntax :
-----------------
Ex:-
SI = PTR/100;
Calling Function :
******************
on SQL prompt :
---------------
method 1:
---------
SIMPLE_INT(1000,2,10)
---------------------
200
method 2 :
----------
RES
------
200
method 3 :
----------
declare
result number;
begin
select simple_int(1000,2,10) into result from dual;
dbms_output.put_line('Simple Interest = ' || result );
End;
/
method 4 :
----------
declare
result number;
begin
result := simple_int(1000,2,10);
dbms_output.put_line('Simple Interest = ' || result );
End;
/
Simple Interest = 200
method 5 :
----------
begin
dbms_output.put_line('Simple Interest = ' || simple_int(1000,2,10));
End;
/
Ex2:-
EMP_EXP(7788)
-------------
41.047
EMP_EXP(9000)
-------------
-1
EMP_DNAME(7788)
-------------------------------------------------------------------------
---------------------------
RESEARCH
EMP_DNAME(7521)
-------------------------------------------------------------------------
---------------------------
SALES
EMP_DNAME(7839)
-------------------------------------------------------------------------
---------------------------
ACCOUNTING
EMP_DNAME(9000)
------------------------------------------------------------
Employ Record Not Exists...
note: Above function returns TRUE(output) to SQL PROMPT but, SQL not
supported BOOLEAN datatype. So To call above function
in PL/SQL block we can call
Declare
flag boolean;
Begin
flag := emp_find( &empno ); -- here function is calling
if flag = true then
dbms_output.put_line( 'Employ Record Exists...');
else
dbms_output.put_line( 'Employ Record Not Exists...');
end if;
End;
/
SQL> /
Enter value for empno: 7369
Employ Record Exists...
SQL> /
Enter value for empno: 9000
Employ Record Not Exists...
begin
if emp_find(&empno) then -- function is calling
dbms_output.put_line( 'Employ Record Exists...');
else
dbms_output.put_line( 'Employ Record Not Exists...');
end if;
End;
/
SQL> /
Enter value for empno: 9000
Employ Record Not Exists...
PL/SQL procedure successfully completed.
table creation :
****************
SUBS
----
rama
INSTR('RAMAKRISHNA','K',1,1)
----------------------------
6
INSTR('RAMAKRISHNA','A',1,1)
----------------------------
2
INSTR('RAMAKRISHNA','A',1,2)
----------------------------
4
Procedure :
------------
OBJECT_NAME
-------------------------------------------------------------------------
---------------------------
SIMPLE_INT
EMP_EXP
EMP_DNAME
EMP_FIND
FNAME
LNAME
MNAME
7 rows selected.
TEXT
-------------------------------------------------------------------------
---------------------------
function Fname( cname varchar2 ) -- ramesh sachin tendulkar
Return Varchar2
is
v_Fname cric_info.fname%type;
Begin
v_fname := substr(cname, 1, Instr(cname, ' ', 1 ,1 )-1 );
return( v_fname );
End fname;
8 rows selected.
** Dropping Functions
Packages :
----------
-> Package is a collection of Variables, Cursors, Procedures &
Functions
-> Packages are used to Improves the performance while accessing sub-
programs(Procedures & Functions) from client location
-> Packages are supports OOPs features like Function OverLoading, Data
Abstraction & Encapsulation
-> Packages will not support any PARAMETERS and Will Not return any
values
I. PACKAGE SPECIFICATION
I. PACKAGE SPECIFICATION :
--------------------------
Package Specification :
***********************
PACKAGE BODY :
**************
-- procedure body
-- Function Body
End my_pack;
/
-- calling procedure
*
ERROR at line 1:
ORA-20001: Employ Record Not Found.
ORA-06512: at "ORA7AM.MY_PACK", line 14
ORA-06512: at line 1
-- Calling Function
MY_PACK.EMP_GRADE(7839)
-----------------------
5
MY_PACK.EMP_GRADE(9000)
-----------------------
0
Function OverLoading :
**********************
Ex:-
Package Specification :
***********************
PACKAGE BODY :
**************
End Fo_pack;
/
FO_PACK.ADDVAL(100,200)
-----------------------
300
FO_PACK.ADDVAL(100,200,500)
---------------------------
800
FO_PACK.ADDVAL('NARESH','IT')
-------------------------------------------------------------
naresh it
Procedure OverLoading :
-----------------------
Calling Procedure :
-------------------
declare
v_cur P1.r_cur;
e emp%rowtype;
Begin
GET_DETAILS( &Deptno, v_cur ); -- calling procedure
loop
fetch v_cur into e;
exit when v_cur%notfound;
dbms_output.put_line( e.empno ||' '|| e.ename||' '||e.job||'
'||e.mgr||' '||e.hiredate||' '||e.sal||' '||e.deptno);
end loop;
close v_cur;
p1.status := 'Program Executed Successfully.';
dbms_output.put_line( p1.status );
End;
/
SQL> /
Enter value for deptno: 30
7499 ALLEN SALESMAN 7698 20-FEB-81 2080 30
7521 WARD SALESMAN 7698 22-FEB-81 1875 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1875 30
7698 BLAKE MANAGER 7839 01-MAY-81 3705 30
7844 TURNER SALESMAN 7698 08-SEP-81 1950 30
7900 JAMES CLERK 7698 03-DEC-81 1425 30
Program Executed Successfully.
OBJECT_NAME
-------------------------------------------------------------------------
---
MY_PACK
FO_PACK
P1
TEXT
-------------------------------------------------------------------------
---------------------------
Package my_pack
is
-- procedure body
-- Function Body
End my_pack;
39 rows selected.
** Dropping Packages
V. WITHDRAW AMOUNT(procedure)
Validations :
*************
V. WITHDRAW AMOUNT :
--------------------
TABLE CREATIONS :
*****************
Bank_Mas :
----------
Bank_Trans :
************
if mobile_cnt>0 then
raise_application_error(-20001, 'Mobileno already registered.');
elsif mail_cnt>0 then
raise_application_error(-20002, 'e-mail already registered.');
elsif upper(p_acc_type) not in ( 'C','S') then
raise_application_error(-20003, 'Invaid Account Type!!!!');
elsif p_bal <1000 then
raise_application_error(-20004, 'Min. Account Opening Balance
Rs.1000/-');
else
Insert into bank_mas values( 'sbi'||(acno_seq.nextval),
upper(p_cname), p_address, p_mobileno,
p_mail_id, p_acc_type,
p_odate, p_bal);
dbms_output.put_line('Account created successfully.');
end if;
End New_Acc;
dbms_output.put_line(rpad(bt.Sacno,10)||rpad(bt.Tdate,10)||rpad(bt.Ttype,
10)||rpad(bt.Tamt,10));
End Loop;
Close Mini_cur;
dbms_output.put_line('***** END OF THE RECORDS *****');
End Mini_stat;
End Bank_Pack;
/
commit;
9 rows selected.
Deposit Amount :
----------------
Withdraw Amt. :
---------------
Tamount Transfer :
******************
BANK_PACK.CHK_BAL('SBI1')
-------------------------
1800
BANK_PACK.CHK_BAL(9000994006)
-----------------------------
2900
MINI STATEMENT :
****************
SQL> Exec Bank_pack.mini_stat('sbi1');
Account Statement :
*******************
TRIGGERS :
**********
-> Triggers are executed when the tables are manipulated by other users
or by other application s/w tools
-> All Created Trigger Bodies are stored in USER_SOURCE ( system table
)
Trigger Parts :
***************
i. Trigger Event :
------------------
Trigger syn:-
*************
NAMED BLOCKS :
--------------
-> All Named Block Programs are start with CREATE statement
SUB-PROGRAMS :
--------------
i. stored procedures
i. Stored Procedures :
----------------------
-> While calling the stored procedures we can pass parameters and
maximum 32 parameters are supported
I. RE-USABILITY :
II. MODULARITY :
adv.
* easy to understand
-> All created stored procedure names are stored in USER_OBJECTS table
( pre-defined table )
-> All stored procedure Bodies are stored in USER_SOURCE table ( pre-
defined table )
syn:-
Ex:-
on sql prompt :
***************
ex:-
syn:-
begin
<procedure_name>;
End;
/
ex:-
Begin
my_proc;
End;
/
Procedure created.
Procedure created.
note:
ex:-
6 rows selected.
7 rows selected.
LINE/COL ERROR
-------- ----------------------------------------------------------------
-
12/5 PLS-00113: END identifier 'EMP_INCR' must match 'EMP_INCR_PROC'
at line 1, column 11
Procedure :
-----------
14 rows selected.
14 rows selected.
14 rows selected.
i. IN
ii. OUT
iii. IN OUT
i. IN :
-------
ex:-
Procedure created.
LINE/COL ERROR
-------- ----------------------------------------------------------------
-
4/8 PL/SQL: Statement ignored
4/8 PLS-00363: expression 'X' cannot be used as an assignment target
ii. OUT :
---------
ex:-
-- write a stored procedure to find sum of two given numbers and return
the output
Calling procedure :
-------------------
ON SQL Prompt :
***************
RES
------
600
SQL> declare
result number;
begin
add_proc(500, 400 , result );
dbms_output.put_line( 'sum of two given numbers = '||result);
end;
/
sum of two given numbers = 900
EX:-
calling procedure :
*******************
declare
v_netsal Number;
Begin
emp_netsal_Proc( &empno, v_netsal); -- calling procedure
dbms_output.put_line('Given Employ Net Sal Rs.'||v_netsal);
End;
/
SQL> /
Enter value for empno: 7521
Given Employ Net Sal Rs.2375
Ex:-
calling procedure :
-------------------
declare
v_grade number;
begin
emp_grade( &empno, v_grade );
dbms_output.put_line( 'Emp Grade is ' || v_grade );
end;
/
SQL> /
Enter value for empno: 7369
Emp Grade is 1
Ex:-
generating aadharnos:
---------------------
SQL> update customer_db set aadharno = 99999+rownum;
14 rows updated.
14 rows selected.
Stored Procedure :
******************
Declare
v_cid customer_db.cid%type;
v_cust_name customer_db.cust_name%type;
v_cust_desig customer_db.cust_desig%type;
v_cust_db customer_db.cust_db%type;
Begin
get_info( &aadharno, v_cid, v_cust_name, v_cust_desig, v_cust_db);
-- calling procedure
dbms_output.put_line( v_cid );
dbms_output.put_line( v_cust_name );
dbms_output.put_line( v_cust_desig );
dbms_output.put_line( v_cust_db );
End;
/
Validations :
-------------
step1 :
Table creation :
----------------
step2 :
-------
Calling procedure :
-------------------
Declare
v_status varchar2(100);
Begin
User_Registration_Proc( &cid, &accno, &username, &password,
&cnf_password, &created_by, v_status );
dbms_output.put_line( v_status );
End;
/
INVALID INPUTS :
-----------------
Declare
v_status varchar2(100);
Begin
User_Registration_Proc( &cid, &accno, &username, &password,
&cnf_password, &created_by, v_status );
dbms_output.put_line( v_status );
End;
/
SQL> /
Enter value for cid: 13
Enter value for accno: 'sbi3'
Enter value for username: 'scott_sbi'
Enter value for password: 'king@123'
Enter value for cnf_password: '123@king'
Enter value for created_by: 'admin'
Enter Password and Cnf. Passwords should be same..
PL/SQL procedure successfully completed.
SQL> /
Enter value for cid: 13
Enter value for accno: 'sbi4'
Enter value for username: 'king_sbi'
Enter value for password: 'king@123'
Enter value for cnf_password: 'king@123'
Enter value for created_by: 'admin'
UserName already Exists.....
SQL> /
Enter value for cid: 13
Enter value for accno: 'sbi3'
Enter value for username: 'scott_sbi'
Enter value for password: 'scott'
Enter value for cnf_password: 'scott'
Enter value for created_by: 'admin'
Min. Length of Password is 6 chars.
calling Procedure :
-------------------
Declare
v_status varchar2(100);
Begin
login_proc( &user_name, &password, v_status ); -- calling Procedure
dbms_output.put_line( v_status );
End;
/
Enter value for user_name: 'king_sbi'
Enter value for password: 'king@123'
Login Successfully.
SQL> /
Enter value for user_name: 'king_sbi'
Enter value for password: 'king'
Invalid UserName/Password
iii. IN OUT :
-------------
ex:-
calling Procedure :
*******************
declare
res number(10) := &res; -- 10
Begin
Inout_proc( res );
dbms_output.put_line( 'Result = ' || res );
end;
/
-> While calling the stored procedures if we are not passing value to
Parameters then by default
specified default values are taken.
ex:-
calling procedure :
*******************
6 rows selected.
Note: In abvoe 2nd example, Dept.Name taken as 'HYD' and LOC taken as
'Unknown', because by default procedures calling according to
positions.
NOTATIONS :
-----------
I. POSITIONAL NOTATIONS
I. POSITIONAL NOTATIONS :
-------------------------
ex:-
ex:-
6 rows selected.
III. MIXED NOTATIONS :
----------------------
ex:-
7 rows selected.
OBJECT_NAME
-------------------------------------------------------------------------
-------------
INOUT_PROC
EMP_NETSAL_PROC
EMP_GRADE
GET_INFO
USER_REGISTRATION_PROC
LOGIN_PROC
ADD_PROC
MY_PROC
DEPT_INS
EMP_INCR_PROC
EMP_DEL
EMP_BONUS_PROC
DEPT_INS_PROC
13 rows selected.
TEXT
-------------------------------------------------------------------------
---------------------------
procedure User_Registration_Proc( p_cid IN number,
p_accno IN varchar2,
p_user_name IN
varchar2, -- king_sbi
p_password IN
varchar2, -- king@123
p_cnf_password IN
varchar2,
p_created_by IN
varchar2,
p_status Out Varchar2
)
Is
Cnt Number;
Begin
Select count(*) Into cnt from bank_user_reg where user_name =
p_user_Name; -- if cnt=1 is exis
ts, cnt=0 not exists
if cnt=1 then
p_status := 'UserName already Exists.....';
elsif ASCII( substr( p_password ,1,1) ) Not Between 65 and 90 and
ASCII( substr( p_password ,1,1) ) Not Between 97 and 122 then
p_status := 'Password should be start with an Alphabet..';
elsif length(p_password) <6 then
p_status := 'Min. Length of Password is 6 chars.';
elsif p_password != p_cnf_password then
p_status := 'Enter Password and Cnf. Passwords should be same..';
elsif p_created_by not in ( 'admin','customer') then
p_status := 'Invalid Role...';
else
Insert into bank_user_reg values( tno_seq.nextval, p_cid, p_accno,
p_user_name , p_password, s
ysdate, p_created_by, 1);
28 rows selected.
** Dropping Procedures :
*************************
i. Modularity
ii. Re-usability
-> All created User Defined function Names are stored in USER_OBJECTS
-> All created User Defined Function Bodies are stored in USER_SOURCE
tables
Function Syntax :
-----------------
Ex:-
SI = PTR/100;
Calling Function :
******************
on SQL prompt :
---------------
method 1:
---------
SQL> select Simple_int(1000,2,10) from dual;
SIMPLE_INT(1000,2,10)
---------------------
200
method 2 :
----------
RES
------
200
method 3 :
----------
declare
result number;
begin
select simple_int(1000,2,10) into result from dual;
dbms_output.put_line('Simple Interest = ' || result );
End;
/
method 4 :
----------
declare
result number;
begin
result := simple_int(1000,2,10);
dbms_output.put_line('Simple Interest = ' || result );
End;
/
method 5 :
----------
begin
dbms_output.put_line('Simple Interest = ' || simple_int(1000,2,10));
End;
/
Ex2:-
EMP_EXP(7788)
-------------
41.047
EMP_EXP(9000)
-------------
-1
EMP_DNAME(7521)
-------------------------------------------------------------------------
---------------------------
SALES
EMP_DNAME(7839)
-------------------------------------------------------------------------
---------------------------
ACCOUNTING
EMP_DNAME(9000)
------------------------------------------------------------
Employ Record Not Exists...
note: Above function returns TRUE(output) to SQL PROMPT but, SQL not
supported BOOLEAN datatype. So To call above function
in PL/SQL block we can call
Declare
flag boolean;
Begin
flag := emp_find( &empno ); -- here function is calling
if flag = true then
dbms_output.put_line( 'Employ Record Exists...');
else
dbms_output.put_line( 'Employ Record Not Exists...');
end if;
End;
/
SQL> /
Enter value for empno: 7369
Employ Record Exists...
SQL> /
Enter value for empno: 9000
Employ Record Not Exists...
begin
if emp_find(&empno) then -- function is calling
dbms_output.put_line( 'Employ Record Exists...');
else
dbms_output.put_line( 'Employ Record Not Exists...');
end if;
End;
/
SQL> /
Enter value for empno: 9000
Employ Record Not Exists...
table creation :
****************
SUBS
----
rama
INSTR('RAMAKRISHNA','K',1,1)
----------------------------
6
INSTR('RAMAKRISHNA','A',1,1)
----------------------------
2
INSTR('RAMAKRISHNA','A',1,2)
----------------------------
4
Procedure :
------------
OBJECT_NAME
-------------------------------------------------------------------------
---------------------------
SIMPLE_INT
EMP_EXP
EMP_DNAME
EMP_FIND
FNAME
LNAME
MNAME
7 rows selected.
TEXT
-------------------------------------------------------------------------
---------------------------
function Fname( cname varchar2 ) -- ramesh sachin tendulkar
Return Varchar2
is
v_Fname cric_info.fname%type;
Begin
v_fname := substr(cname, 1, Instr(cname, ' ', 1 ,1 )-1 );
return( v_fname );
End fname;
8 rows selected.
** Dropping Functions
Packages :
----------
-> Packages are used to Improves the performance while accessing sub-
programs(Procedures & Functions) from client location
-> Packages are supports OOPs features like Function OverLoading, Data
Abstraction & Encapsulation
I. PACKAGE SPECIFICATION
I. PACKAGE SPECIFICATION :
--------------------------
Package Specification :
***********************
PACKAGE BODY :
**************
-- procedure body
-- Function Body
End my_pack;
/
-- calling procedure
*
ERROR at line 1:
ORA-20001: Employ Record Not Found.
ORA-06512: at "ORA7AM.MY_PACK", line 14
ORA-06512: at line 1
-- Calling Function
MY_PACK.EMP_GRADE(7369)
-----------------------
1
MY_PACK.EMP_GRADE(7839)
-----------------------
5
MY_PACK.EMP_GRADE(9000)
-----------------------
0
Function OverLoading :
**********************
Ex:-
Package Specification :
***********************
PACKAGE BODY :
**************
End Fo_pack;
/
FO_PACK.ADDVAL(100,200)
-----------------------
300
FO_PACK.ADDVAL(100,200,500)
---------------------------
800
FO_PACK.ADDVAL('NARESH','IT')
-------------------------------------------------------------
naresh it
Procedure OverLoading :
-----------------------
declare
v_cur P1.r_cur;
e emp%rowtype;
Begin
GET_DETAILS( &Deptno, v_cur ); -- calling procedure
loop
fetch v_cur into e;
exit when v_cur%notfound;
dbms_output.put_line( e.empno ||' '|| e.ename||' '||e.job||'
'||e.mgr||' '||e.hiredate||' '||e.sal||' '||e.deptno);
end loop;
close v_cur;
p1.status := 'Program Executed Successfully.';
dbms_output.put_line( p1.status );
End;
/
SQL> /
Enter value for deptno: 30
7499 ALLEN SALESMAN 7698 20-FEB-81 2080 30
7521 WARD SALESMAN 7698 22-FEB-81 1875 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1875 30
7698 BLAKE MANAGER 7839 01-MAY-81 3705 30
7844 TURNER SALESMAN 7698 08-SEP-81 1950 30
7900 JAMES CLERK 7698 03-DEC-81 1425 30
Program Executed Successfully.
OBJECT_NAME
-------------------------------------------------------------------------
---
MY_PACK
FO_PACK
P1
TEXT
-------------------------------------------------------------------------
---------------------------
Package my_pack
is
-- procedure body
-- Function Body
End my_pack;
39 rows selected.
** Dropping Packages
V. WITHDRAW AMOUNT(procedure)
Validations :
*************
V. WITHDRAW AMOUNT :
--------------------
TABLE CREATIONS :
*****************
Bank_Mas :
----------
Bank_Trans :
************
if mobile_cnt>0 then
raise_application_error(-20001, 'Mobileno already registered.');
elsif mail_cnt>0 then
raise_application_error(-20002, 'e-mail already registered.');
elsif upper(p_acc_type) not in ( 'C','S') then
raise_application_error(-20003, 'Invaid Account Type!!!!');
elsif p_bal <1000 then
raise_application_error(-20004, 'Min. Account Opening Balance
Rs.1000/-');
else
Insert into bank_mas values( 'sbi'||(acno_seq.nextval),
upper(p_cname), p_address, p_mobileno,
p_mail_id, p_acc_type,
p_odate, p_bal);
dbms_output.put_line('Account created successfully.');
end if;
End New_Acc;
dbms_output.put_line(rpad(bt.Sacno,10)||rpad(bt.Tdate,10)||rpad(bt.Ttype,
10)||rpad(bt.Tamt,10));
End Loop;
Close Mini_cur;
dbms_output.put_line('***** END OF THE RECORDS *****');
End Mini_stat;
-- Procedure body for to generate Account Statement
End Bank_Pack;
/
commit;
9 rows selected.
EXECUTE PACKAGE PROGRAME:
-----------*************
Deposit Amount :
----------------
Withdraw Amt. :
---------------
Tamount Transfer :
******************
BANK_PACK.CHK_BAL('SBI1')
-------------------------
1800
BANK_PACK.CHK_BAL(9000994006)
-----------------------------
2900
MINI STATEMENT :
****************
SQL> Exec Bank_pack.mini_stat('sbi1');
Account Statement :
*******************
TRIGGERS :
**********
-> Triggers are executed when the tables are manipulated by other users
or by other application s/w tools
-> All Created Trigger Bodies are stored in USER_SOURCE ( system table
)
Trigger Parts :
***************
i. Trigger Event :
------------------
Trigger syn:-
*************
dept: -- step 3
-----
:deptno=50
:dname=Maths
:loc=Hyd
Before Insert
Before Update
Before Delete :NEW.
After Insert
After Update
After Insert
After Update :OLD.
After Delete
Ex:-
dept :
------
:deptno=50
:dname=MATHS
:loc=Hyd
Trigger created.
SQL> Insert Into dept values( 50, 'maths', 'Hyd');
1 row created.
rollback segment:
-----------------
sql> Update emp Set sal = 2500 where empno = 7788; -- step 2
Trigger :
---------
Trigger created.
1 row updated.
Ex 3:-