Oracle 6i Report Tutorials
Oracle 6i Report Tutorials
Venkat
Mail: [email protected]
• Schema objects
– Tables
– Views
– Sequences
– Synonyms
– Indexes
– Clusters
• Sub queries
– Single row sub queries
– Multi row sub queries
– Correlated sub queries
– Uses of sub queries
Object Description
• User Tables
– Collection of tables created and
maintained by the user
– Contain user information
• Data Dictionary
– Collection of tables created and
maintained by the Oracle server
– Contain database information
7934 207369
MILLER
SMITH
CLERK
CLERK 7902 17-DEC-80 800 20
7876
7788 ADAMS
SCOTT ANALYST
CLERK 7566 12-JAN-83
7788 09-DEC-82 3000
1100 20
20
7876 ADAMS CLERK 7788 12-JAN-83 1100 20
7369
7934 SMITH
MILLER CLERK
CLERK 7782 17-DEC-80
7902 23-JAN-82 1300
800 10
20
7902 FORD ANALYST 7566 03-DEC-81 3000
20
1-13 7698 BLAKE
Copyright MANAGER
CSC India, 2001. All 7839 01-MAY-81
rights reserved. 2850
30
Simple Views
and Complex Views
Feature Simple Views Complex Views
SQL*Plus
USER_VIEWS
SELECT *
EMPVU10
FROM empvu10;
SELECT empno, ename, job
FROM emp
WHERE deptno = 10;
7839 KING PRESIDENT
7782 CLARK MANAGER EMP
7934 MILLER CLERK
• Simple Index
• Unique Index
• Bitmap Index
ROLLBACK to Savepoint B
ROLLBACK to Savepoint A
ROLLBACK
1-61 Copyright CSC India, 2001. All rights reserved.
100 SMITH 20000
101 ALLEN 25000 Commit
102 JAMES 20000
103 MILLER 30000 Savepoint A
105 BLAKE 35000
106 JONES 20000 Savepoint B
107 CLARK 25000
108 KING 40000
SQL>Rollback;
SQL>Rollback to A;
SQL> UPDATE...
SQL> SAVEPOINT update_done;
Savepoint created.
SQL> INSERT...
SQL> ROLLBACK TO update_done;
Rollback complete.
Statement Description
ENAME DNAME
------ ----------
KING ACCOUNTING
“Cartesian BLAKE ACCOUNTING
product: ...
KING RESEARCH
14*4=56 rows” BLAKE RESEARCH
...
56 rows selected.
No employee in the
OPERATIONS department
WORKER.ENAME||'WORKSFOR'||MANAG
-------------------------------
BLAKE works for KING
CLARK works for KING
JONES works for KING
MARTIN works for BLAKE
...
13 rows selected.
Main Query
Subquery
?
“What is Jones’ salary?”
ENAME
----------
KING
FORD
SCOTT
• Multiple-row subquery
Main query
returns CLERK
Subquery
MANAGER
• Multiple-column subquery
Main query
returns
Subquery CLERK 7900
MANAGER 7698
1-97 Copyright CSC India, 2001. All rights reserved.
Single-Row Subqueries
• Return only one row
• Use single-row comparison operators
Operator Meaning
= Equal to
ENAME JOB
---------- ---------
MILLER CLERK
ERROR:
ORA-01427: single-row subquery returns more than
one row
no rows selected
Subquery
SALESMAN 30
MANAGER 10
CLERK 20
SQL> Update emp set sal=4000 where deptno=(select deptno from dept
where dname=‘SALES’);
Sql> Select ename, deptno,sal from emp WHERE sal> ALL (select
max(sal) from emp group by deptno);
Sql> Select ename, deptno,sal from emp WHERE sal> ALL (select
max(sal) from emp where deptno in(20,30) group by deptno);
• Block Structure
PL/SQL is a block-structured language. That is, the basic
units (procedures, functions, and anonymous blocks) that
make up a PL/SQL program are made of PL/SQL blocks.
•Subprograms
PL/SQL has two types of subprograms called procedures and
functions, which can take parameters and be invoked (called).
•Packages
PL/SQL lets you bundle logically related types, variables,
cursors, and subprograms into a package.
•Error Handling
Oracle has a robust error-handling mechanism. It allows us to
create custom error code as well.
Better performance
Without PL/SQL, Oracle must process SQL statements one at a time.
Each SQL statement results in another call to Oracle and higher
performance overhead. In a networked environment, the overhead can
become significant. Every time a SQL statement is issued, it must be
sent over the network, creating more traffic. However, with PL/SQL,
an entire block of statements can be sent to Oracle at one time. This can
drastically reduce communication between your application and Oracle.
• PL/SQL stored procedures are compiled once and stored in executable form, so
procedure calls are quick and efficient. Also, stored procedures, which
execute in the server, can be invoked over slow network connections with
a single call. That reduces network traffic and improves round-trip
response times.
•Full portability
Applications written in PL/SQL are portable to any operating system
and platform on which Oracle runs. In other words, PL/SQL
programs can run anywhere Oracle can run; you need not tailor
them to each new environment. That means you can write portable
program libraries, which can be reused in different environments.
DECLARE
<Variable Declarations>;
BEGIN
EXCEPTION
<Error Handling>;
END;
2.Executable part:
Composite Variables:
Made up of multiple values, such as a record or collection (PL/SQL
tables, NESTED tables and VARRAY’S).
Syntax:
Variable_name datatype [CONSTANT] [NOT NULL] [:= | DEFAULT initial_value];
Examples:
V_hiredate date;
V_deptno Number(2) Not Null:=10;
V_name Varchar2(15):=‘SMITH’;
V_comm Constant Number:=500;
V_bonus Number Default 500;
2. %ROWTYPE
An Oracle Supplied Packaged Procedure Used to display data from PL/SQL block
Must be enabled at SQL*PLUS with
SET SERVEROUTPUT ON
Example:
Declare
V_annual_sal Number:=60000;
V_sal Number;
Begin
V_sal:=V_annual_sal/12;
Dbms_Output.put_line (‘The monthly Sal is ‘||V_sal);
End;
Declare
N number:=5;
P number;
Begin
P:=power(N,2);
dbms_output.put_line ('the power value of '||N||' is '||P);
End;
Declare
V_Deptno Dept.deptno%type:=&v_deptno;
V_Dname Dept.dname%type:=‘&v_dname;
V_loc Dept.loc%type:=‘&loc’;
Begin
Insert into Dept Values (V_deptno,V_Dname,V_loc);
Commit;
End;
Declare
V_Ename Emp.Ename%type:='&v_ename';
V_newsal Number(10,2):=&newsal;
Begin
Update Emp set Sal=V_newsal where Ename=V_Ename;
Rollback;
End;
Declare
Emp_rec Emp%rowtype;
Begin
Select * into Emp_rec from Emp where ename=‘&ename’;
Dbms_Output.Put_Line(Emp_rec.Empno || ' '|| Emp_rec.Ename);
End;
1. Conditional Control
2. Iterative Control
3. Sequential Control
Declare
N Number:=&no;
Begin
If N Between 0 and 10 then
Dbms_output.put_line(N||' b/w 0 and 10');
Elsif N Between 11 and 20 then
Dbms_output.put_line(N||' b/w 11 and 20');
Else
Dbms_output.put_line(N||' out of range ');
End if;
End;
DECLARE
Acct_balance NUMBER (11, 2);
Acct CONSTANT NUMBER (4):= 3;
Debit_amt CONSTANT NUMBER (5, 2):= 500.00;
BEGIN
SELECT bal into Acct_balance from BANK
WHERE Accno = Acct FOR UPDATE OF bal;
IF Acct_balance >= Debit_amt THEN
UPDATE BANK SET bal = bal - Debit_amt
Where Accno =acct;
ELSE
INSERT into TEMP1 values (Acct, Acct_balance, 'Insufficient funds');
END IF;
COMMIT;
END;
Types of Loops;
1. Simple Loop
2. While Loop
3. For Loop
EXIT Statement:
Used to Close the loop
DECLARE
Dept_rec dept%rowtype;
Dno number:=0;
BEGIN
LOOP
Dno:=dno+10;
Select * into dept_rec from DEPT where deptno =dno;
dbms_output.put_line (dept_rec.deptno||' '||dept_rec.dname||' '||dept_rec.loc);
EXIT when dno =40; --closes the loop conditionally
END LOOP;
END;
Syntax:
While <condition> loop
<Statements>;
End loop;
Example:
DECLARE
A number;
BEGIN
WHILE nvl (A, 0) <10 LOOP
A:= Nvl (A, 0) +1;
Dbms_output.put_line (A);
END LOOP;
END;
DECLARE
X NUMBER:= 10;
BEGIN
FOR I IN 1..X LOOP
IF MOD (I, 2) = 0 THEN -- I is even
INSERT INTO temp VALUES (I, I||' is even');
ELSE
INSERT INTO temp VALUES (I, I||' is odd');
END IF;
IF I=X THEN
DBMS_OUTPUT.PUT_LINE (I||' ROWS INSERTED');
END IF;
END LOOP;
END;
DECLARE
A number:=&no;
B number:=0;
BEGIN
For I in reverse 1..10 loop
B:=A*I;
Dbms_output.put_line (a|| ‘ * '||I||' = '||B);
End loop;
END;
Exception is an error or warning in pl/sql that is raised during the Execution of block.
When it is raised?
Predefined Exceptions
• Raised implicitly by Oracle when pl/sql program violates oracle rule.
Non Predefined Exceptions
• Declared in the Declarative section and Oracle raises implicitly
User defined Exceptions
• User defined exceptions must be declared and raised explicitly by RAISE
statements.
• NO_DATA_FOUND
• TOO_MANY_ROWS
• DUP_VAL_ON_INDEX
• INVALID_NUMBER
• ZERO_DEVIDE
• INVALID_CURSOR
• STORAGE_ERROR
• CURSOR_ALREADY_OPEN
• CASE_NOT_FOUND
• PROGRAM_ERROR
CURSOR_ALREADY_OPEN ORA-06511
DUP_VAL_ON_INDEX ORA-00001
INVALID_CURSOR ORA-01001
INVALID_NUMBER ORA-01722
LOGIN_DENIED ORA-01017
NO_DATA_FOUND ORA-01403
NOT_LOGGED_ON ORA-01012
PROGRAM_ERROR ORA-06501
STORAGE_ERROR ORA-06500
TIMEOUT_ON_RESOURCE ORA-00051
TOO_MANY_ROWS ORA-01422
VALUE_ERROR ORA-06502
ZERO_DIVIDE ORA-01476
DECLARE
Emp_rec emp%rowtype;
v_empno number:=&eno;
BEGIN
SELECT * into emp_rec from emp where empno =v_empno;
dbms_output.put_line(emp_rec.ename);
EXCEPTION
WHEN NO_DATA_FOUND then
dbms_output.put_line ('empno not exist');
END;
DECLARE
emp_rec emp%rowtype;
v_deptno emp.deptno%type:=&v_deptno;
BEGIN
SELECT * into emp_rec from emp where deptno =v_deptno;
dbms_output.put_line(emp_rec.ename||' '||emp_rec.sal);
EXCEPTION
WHEN TOO_MANY_ROWS Then
dbms_output.put_line ('Trying to fetch more than one row');
END;
DECLARE
A number:=&no;
B number:=0;
BEGIN
A:=A/B;
dbms_output.put_line(A);
EXCEPTION
when ZERO_DIVIDE then
Null;
END;
/
BEGIN
INSERT into dept values (&dno, '&dname', '&loc');
dbms_output.put_line('1 Row created');
EXCEPTION
when DUP_VAL_ON_INDEX then
dbms_output.put_line ('trying to enter duplicate deptno');
END;
DECLARE
V_ename number;
BEGIN
Select Ename into V_ename from EMP where empno =7566;
dbms_output.put_line (V_ename);
EXCEPTION
When VALUE_ERROR then
dbms_output.put_line ('Value Error ');
END;
DECLARE
Grade char (1):='&Grade';
Appraisal varchar2 (20);
BEGIN
CASE
When Grade = 'A' then Appraisal:='Excellent';
When Grade = 'B' then Appraisal:='Very Good';
END case;
dbms_output.put_line (Appraisal);
EXCEPTION
When CASE_NOT_FOUND Then
Dbms_output.put_line ('Case Not Matching');
END;
DECLARE
V_ename EMP.Ename%type:='&ename';
V_comm number;
Null_comm Exception;
BEGIN
Select comm into V_comm from EMP where Ename= v_ename;
DECLARE
emp_rec emp%rowtype;
v_deptno emp.deptno%type:=&v_deptno;
BEGIN
SELECT * into emp_rec from emp where deptno =v_deptno;
dbms_output.put_line(emp_rec.ename||' '||emp_rec.sal);
EXCEPTION
When OTHERS Then
dbms_output.put_line ('Trying to fetch more than one row');
END; 1-165 Copyright CSC India, 2001. All rights reserved.
Functions for Trapping Exceptions
DECLARE
emp_rec emp%rowtype;
v_empno number:=&eno;
BEGIN
SELECT * into emp_rec from emp where empno =v_empno;
dbms_output.put_line(emp_rec.ename);
EXCEPTION
When OTHERS then
dbms_output.put_line (SQLCODE||’ ‘||SQLERRM);
END;
DECLARE
No number;
BEGIN
NULL;
BEGIN -- sub-block begins
SELECT 10/0 INTO no FROM dual;
EXCEPTION
WHEN ZERO_DIVIDE THEN
dbms_output.put_line ('zero divide');
END; -- sub-block ends
Syntax:
PRAGMA EXCEPTION_INIT (exception_name, -Oracle_error_number);
DECLARE
RESOURCE_BUSY Exception;
Pragma Exception_Init (RESOURCE_BUSY, -54);
V_Sal Number;
BEGIN
Select sal into V_Sal from emp where empno = 7566 for update of sal NO WAIT;
dbms_output.put_line(v_sal);
Exception
when RESOURCE_BUSY then
Dbms_Output..Put_Line ('Resource is Busy');
End;
BEGIN
Declare
X Number := ‘ABC';
Begin --inner block starts
Dbms_Output.Put_Line(X);
Exception
When Value_Error then
Dbms_Output.Put_Line('Value Error in Innerblock');
End; -- inner block ends
EXCEPTION
When Value_Error then
Dbms_Output.Put_Line('Value Error in Outerblock');
END;
DECLARE
v_empno emp.empno%type:=&empno;
v_comm number;
BEGIN
SELECT comm INTO v_comm FROM EMP WHERE empno =
v_empno;
IF v_comm IS NULL THEN
-- Issue user-defined error message.
RAISE_APPLICATION_ERROR (-20101, 'Comm is missing');
ELSE
dbms_output.put_line(v_comm);
END IF;
END;
Types of Cursors
Static Cursor:
• Implicit cursor
• Explicit cursor
Dynamic cursors:
Ref cursor
• Weak cursor
• Strong cursor
• Explicit Cursors are used for queries that return multiple rows.
• Explicit Cursors must be declared.
Syntax
Cursor <Cursor_Name> is <Select_Statement>;
Ex:
Cursor C1 is Select * from Emp where deptno =10;
Cursor Control
DECLARE
V_deptno Emp.deptno%type:=&deptno;
Cursor c1 is select * from EMP where deptno =V_deptno;
Emp_rec c1%rowtype;
BEGIN
OPEN C1;
LOOP
FETCH c1 into Emp_rec;
Dbms_output.put_line (Emp_rec.empno||'
'||Emp_rec.ename);
EXIT;
END LOOP;
CLOSE C1;
EXCEPTION
When OTHERS Then
Dbms_output.put_line (SQLCODE||' '||SQLERRM);
END;
DECLARE
Cursor C1 is select * from Emp where deptno=&deptno;
Emp_rec C1%rowtype;
BEGIN
OPEN C1;
LOOP
FETCH C1 into Emp_rec;
EXIT WHEN C1%NOTFOUND;
Dbms_output.put_line(Emp_rec.empno||' '||Emp_rec.ename);
END LOOP;
CLOSE C1;
END;
DECLARE
Emp_rec Emp%rowtype;
Cursor C1 is select * from Emp;
v_count number;
BEGIN
OPEN C1;
LOOP
FETCH C1 into Emp_rec;
v_count:=C1%rowcount;
Dbms_output.put_line(Emp_rec.empno||' '||Emp_rec.ename);
Exit when C1%rowcount=5;
END LOOP;
Dbms_output.put_line(v_count||' rows selected ');
Close c1;
EXCEPTION
when others then
dbms_output.put_line(sqlcode||' '||sqlerrm);
END;
DECLARE
Emp_rec Emp%Rowtype;
Cursor c1 is Select * from Emp;
V_count number;
BEGIN
FOR I IN C1 LOOP
V_count:=C1%rowcount;
Dbms_output.put_line(I.EMPNO||' '||I.ENAME);
EXIT When C1%rowcount>5;
END LOOP;
--Dbms_output.put_line(C1%rowcount||' Rows selected ');
Dbms_output.put_line(V_count||' Rows selected ');
EXCEPTION
When INVALID_CURSOR Then
Dbms_output.put_line ('Invalid Cursor');
When OTHERS THEN
Dbms_output.put_line(SQLCODE||' '||SQLERRM);
END;
DECLARE
Cursor C1 IS Select * from Emp FOR UPDATE OF SAL;
BEGIN
FOR I IN C1 LOOP
IF I.Comm is null Then
UPDATE Emp SET comm= Sal*0.1 WHERE CURRENT OF C1;
END IF;
END LOOP;
EXCEPTION
When OTHERS Then
Dbms_output.put_line(SQLCODE||' '||SQLERRM);
END;
DECLARE
Bonus Number(10,2);
BEGIN
FOR emp_rec IN (SELECT Empno, Sal, comm FROM Emp) LOOP
bonus := (Emp_rec.sal * 0.05) + NVL(Emp_rec.comm,1) * 0.25;
INSERT INTO Bonuses VALUES (Emp_rec.empno, Bonus);
END LOOP;
COMMIT;
END;
BEGIN
Dbms_output.put ('MAXSAL'||' '||'MINSAL'||' '||'DEPTNO');
FOR I IN C1 LOOP
Dbms_output.put_line(' ');
Dbms_output.put_line(I.MAX_SAL||' '||I.MIN_SAL||' '||I.DEPTNO);
END LOOP;
EXCEPTION
When OTHERS THEN
Dbms_output.put_line(SQLCODE||' '||SQLERRM);
END;
REF cursor :
A cursor variable is a reference type. A reference type is similar to a pointer.
It can name different storage locations as the program runs. In order to use
the reference type, the variable has to be declared and storage has to be
allocated. REF cursors are further classified based on the return type
1. Strong Cursor : A strong cursor is a cursor whose return type is specified.
2. Weak Cursor : A weak cursor is a cursor whose return type is not specified.
A Subprogram:
• Syntax:
Ex:
Declare
V_deptno Emp.empno%type:=&v_deptno;
Begin
GET_EMP_DET(V_deptno);
End;
Ex2:
CREATE or Replace Procedure Emp_Insert
(V_empno in number, V_ename in varchar2) is
Procedure Emp_Log is
BEGIN
INSERT into LOG Values (User, Sysdate);
END Emp_Log;
BEGIN
INSERT into EMP (Empno, Ename) Values (V_empno, V_ename);
Emp_Log;
EXCEPTION
When Others then
Dbms_output.put_line (sqlcode||' '||sqlerrm);
END Emp_Insert;
END [name];
Pack_Spec:
Ex3:
SQL> BEGIN
For I in Emp_pack.c1 Loop
Emp_pack.Get_empsal(I.Ename);
End Loop;
END;
Ex4:
SQL> BEGIN
Emp_Pack.V_totsal:=Emp_Pack.Get_totsal;
Dbms_output.put_line(Emp_Pack.V_totsal);
END;
Advantages of Triggers
•Auditing transactions
•Prevent invalid transactions
•Enforce complex business rules
•Enforce complex security authorizations
•Provide transparent event logging
•Automatically generate derived column values
•Enable building complex views that are updatable
•Track system events
Procedures and triggers differ in the way that they are invoked.
• A procedure is explicitly executed by a user, application, or
trigger.
• Triggers (one or more) are implicitly fired (executed) by
Oracle when a triggering INSERT, UPDATE, or DELETE
statement is issued, no matter which user is connected or
which application is being used.
Application Trigger:
•Fires whenever an event occurs with a particular application
Database Trigger:
<Trigger body>
Trigger Timing:
• BEFORE
• AFTER
• INSTEAD OF
Triggering Event
• INSERT
• UPDATE
• DELETE
Trigger type:
• STATEMENT
• ROW
Trigger body:
• Complete PL/SQL block
BEGIN
End if;
END;
• Used to reference the value of the column before and after the data
change by prefixing it with the OLD and NEW qualifiers
DECLARE
sal_diff number;
BEGIN
sal_diff := :new.Sal - :old.sal;
Dbms_output.put('Old salary: ' || :old.sal);
Dbms_output.put (' New salary: ' || :new.sal);
Dbms_output.put_line(' Difference ' || sal_diff);
END;
END;
BEGIN
Raise_application_error(-20000,'sorry');
END;