Beruflich Dokumente
Kultur Dokumente
Quick Reference
1.Triggers
There are two kinds of triggers basically.
(1) Row Level Triggers
(2) Statement Level Triggers
It can be again broadly classified as follows
BEFORE INSERT
AFTER INSERT
BEFORE UPDATE
Row Level AFTER UPDATE
BEFORE DELETE
AFTER DELETE
BEFORE INSERT
AFTER INSERT
Statement BEFORE UPDATE
Level AFTER UPDATE
BEFORE DELETE
AFTER DELETE
2. Cursor
Oracle server uses work areas called private SQL areas to execute SQL statements and to
store processing information. PL/SQL cursors can be used to name a private SQL area
and access its stored information.
1. %found
2. %notfound
3. %isopen
4. %rowcount
4. SQL Commands
1. DQL – Data query Language (select)
2. DML – Data Manipulation Language (insert, update, delete)
3. DDL – Data Definition Language (create, alter, drop, truncate)
4. TCL – Transaction Control Language (commit, rollback, savepoint)
5. DCL – Data Control Language (grant, revoke)
TRUNCATE DELETE
Truncate reuse storage will retain the Rollback is possible for delete as it
space creates rollback segments
Truncate cannot be conditional. Delete can be conditional.
Truncate resets high-water mark if drop Delete don’t reset.
storage option is given.
6. Joins
Joins are used to combine rows from two or more Tables. There are different kinds of
Joins
1. Self Join
2. Equi Join/Inner Join(Natural Join)
3. Outer Joins (Left/Right/Full)
4. Cross Join
To explain two table are used. See the Structure and data for the tables
• EMPB
• DPTB
3
SQL>desc empb;
Name Null? Type
------------------------------- -------- ----
ID NUMBER
NAME CHAR(10)
DPT NUMBER
MNG NUMBER
SQL>desc dptb;
Name Null? Type
------------------------------- -------- ----
DPT NUMBER
DPT_NAME CHAR(10)
3 rows selected.
DPT DPT_NAME
------------------------- ----------
10 uuu
15 vvv
20 www
25 xxx
30 yyy
5 rows selected.
1. Self Join
3 rows selected.
4
Combines records that satisfy the Join Condition in both the table.
3 rows selected.
But if you give any of the above query without Join conditions as follows
15 rows selected.
3. Outer Joins
When we are in need of retrieving all the rows from One Table and only those staisfy the
join conditions from the second Table, we need to fill the Empty Part the second one with
NULL. We use outer join (+) for this purpose.
5
See the following Query. It is a Left Outer Join as the ‘+’ symbol is on left hand side of
the join. And when it is on the Right hand side it is called Right Outer Join.
5 rows selected.
In the above query result it is clear that as the Department Numbers 20, 30 are not there
with EMPB table got filled with null and the records from DPTB table is full.
For full outer joine We use the key word ‘ FULL OUTER JOIN’ (Only in 9i)
4. Corss Join
15 rows selected.
• Hash Join : The Hash join will be used, if there are no adequate indexes on the joined
columns.
6
GLOBAL_NAME
--------------------------------
COPDEV.WORLD
1 row selected.
9. Duplicate Row
SQL>select * from emp where rowid not in(select min(rowid) from emp group by id);
This Query retrieves all the duplicate rows based ID ( if any ID is repeated). From the
second occurance onwards.
10. Greatest 5
SQL>select sal from (select sal from emp order by sal desc)where rownum <=5;
1. UNION
2. UNION ALL (Duplicates)
3. INTERSECT
4. MINUS
1. UNION
The Sep operators UNION is used to combine two or more select Queries.
Here the Data type and number of colums in every select query should match.
7
2. UNION ALL
The Sep operators UNION ALL is used to combine two or more select Queries.
Here the Data type and number of colums in every select query should match.
Union All retrieves Duplicates records
3. INTERSECT
The set Operator INTERSECT is used to retrieve only the common rows from two or
more select queries. The Data type and number of colums in every select query should
match.
4. MINUS
The Set operator MINUS retrieves all the records from the first query that are not there
int the Second query. The Data type and number of colums in every select query should
match.
Refer the tables used for JOINS and see the following quries
DPT
-------------------------
20
30
2 rows selected.
DPT
-------------------------
10
15
20
25
30
5 rows selected.
SQL>select dpt from dptb union all select dpt from empb;
DPT
-------------------------
10
15
20
25
30
10
8
15
25
8 rows selected.
DPT
-------------------------
10
15
25
3 rows selected.
Here it is not necessary that the field name of both the quries should be the same.
Only thing is the the data type should be the same.
1. MIN()
2. MAX()
3. COUNT()
4. AVG()
5. SUM()
5 rows selected.
Refer the Tables given in the Join section. Here whenever the ID is NULL it gets
substited with ‘0’ and whenever the NAME is NULL getting substitued with
‘NOBODY’.
9
EMP_DPT
------------------------------------------------
10 --> uuu
15 --> vvv
25 --> nnn
3 rows selected.
Refer Tables given in the Join Section. Here when the Department is ‘10’ it gives ‘uuu’
and when the department ‘15’ it gives ‘vvv’ and for rest(whatever is the department) it
gives ‘nnn’ which is optional.
The date formate basically depends on the NLS_DATE parameter setting in init.ora
SYSDATE
----------------------------
9/23/2004 9:57:47 PM
1 row selected.
TRUNC(SYSDA
------------------------
9/23/2004
1 row selected.
10
SYSDATE-2
-----------
9/21/2004 10:05:23 PM
1 row selected.
SYSDATE+2
-----------
9/25/2004 10:05:23 PM
1 row selected.
ZZ
-----------
23-sep-2004
1 row selected.
SYSDATE-(SYSDATE-1)
------------------------------------
1
1 row selected.
SYSDATE-(SYSDATE+5)
-------------------------
-5
1 row selected.
SYSDATE-SYSDATE
-------------------------
11
1 row selected.
NEXT_DAY('1
-----------
1/5/2004
1 row selected.
ADD_MONTHS(
-----------
11/1/2003
1 row selected.
LAST_DAY('1
-----------
1/31/2004
1 row selected.
GREATEST('
----------
2-JAN-2004
1 row selected.
12
BANNER
-----------------------------------------------------------
Oracle8i Enterprise Edition Release 8.1.6.1.0 - Production
PL/SQL Release 8.1.6.0.0 - Production
CORE 8.1.6.0.0 Production
TNS for 32-bit Windows: Version 8.1.6.0.0 - Production
NLSRTL Version 3.4.1.0.0 - Production
5 rows selected.
sql>desc dual;
Name Null? Type
------------------------------- -------- ----
DUMMY VARCHAR2(1)
<<identifier>>
Eg: <<labelOne>>
Goto labelOne;
13
19. RefCursor
--------------------------------------------------------
create or replace package body pkg as
procedure p1(x out ref_cur) is
c ref_cur;
y emp%rowtype;
begin
open c for select * from emp;
loop
fetch c into y;
exit when c%notfound;
dbms_output.put_line(y.id || ' ' || y.name || ' ' || y.dpt || ' ' || y.sal );
end loop;
exception
when others then
dbms_output.put_line(sqlerrm);
end;
end pkg;
-------------------------------------------------
Quick Reference
1. Exception Handling
PL/SQL block is successfully ended
PL/SQL block is terminated with unhandled exception
What is Exception?
It is an error condition, which terminates the execution of a block. It is a run
time condition.
Types of Exceptions
3 types of Exceptions
EXAMPLES
(CREATE TABLE ERR_MSG (MESSAGE VARCHAR2(250));)
DECLARE
V_ENAME EMPLOYEES.LAST_NAME%TYPE;
V_SAL EMPLOYEES.SALARY%TYPE:=&P_SAL;
BEGIN
SELECT LAST_NAME
INTO V_ENAME
FROM EMPLOYEES
WHERE SALARY=V_SAL;
INSERT INTO
ERR_MSG(MESSAGE)
VALUES (V_ENAME||'-'||TO_CHAR(V_SAL));
EXCEPTION
WHEN NO_DATA_FOUND THEN
INSERT INTO ERR_MSG(MESSAGE)
VALUES ('NO EMPLOYEE WITH A SALARY OF '||TO_CHAR(V_SAL));
EXAMPLE
VARIABLE G_MESSAGE VARCHAR2(50)
DECLARE
V_SAL EMPLOYEES.SALARY%TYPE:=&P_SAL;
15
V_LOW_SAL EMPLOYEES.SALARY%TYPE:=V_SAL-100;
V_HIGH_SAL EMPLOYEES.SALARY%TYPE:=V_SAL+100;
V_NO_EMP NUMBER(7);
E_NO_EMP_RETURNED EXCEPTION;
E_MORE_THAN_ONE_EMP EXCEPTION;
BEGIN
SELECT COUNT(LAST_NAME)
INTO V_NO_EMP
FROM EMPLOYEES
WHERE SALARY BETWEEN V_LOW_SAL AND V_HIGH_SAL;
IF V_NO_EMP=0
THEN
RAISE E_NO_EMP_RETURNED;
ELSIF V_NO_EMP>1
THEN
RAISE E_MORE_THAN_ONE_EMP;
END IF;
EXCEPTION
WHEN E_NO_EMP_RETURNED THEN
:G_MESSAGE:=’THERE IS NO EMPLOYEE SALARY BETWEEN ‘||
TO_CHAR(V_LOW_SAL)||’ AND ‘||TO_CHAR(V_HIGH_SAL);
EXAMPLE 1
-2292 INTEGRITY CONSTRAINT VIOLATION
DEFINE P_DEPTNO=199
DECLARE
E_EMPS_REMAINING EXCEPTION;
PRAGMA EXCEPTION_INIT(E_EMPS_REMAINING, -2292);
BEGIN
DELETE FROM
DEPARTMENTS
WHERE DEPARTMENT_ID=&P_DEPTNO;
COMMIT;
EXCEPTION
WHEN E_EMPS_REMAINING THEN
16
RAISE: Used to raise user-defined exceptions also can raise an exception where the
exception is to be raised forcefully.
Propagation of Exceptions
/* BLOCK A */
DECLARE
…..
BEGIN
…..
EXCEPTION
/* BLOCK B */
DECLARE
….
BEGIN
….
EXCEPTION
….. (EXCEPTION-1)
END;
…… (EXCEPTION-2)
END;
Note:
If error occurs in Block B Exception-1 will be raised if Exception-1 is not present then
control will be passed to Exception-2 of block A
EXAMPLE
DECLARE
V_ERROR_CODE NUMBER;
V_ERROR_MESSAGE VARCHAR2(255);
BEGIN
…………………
…………………
EXCEPTION
…………………
…………………
WHEN OTHERS THEN
ROLLBACK;
V_ERROR_CODE:=SQLCODE;
V_ERROR_MESSAGE:=SQLERRM;
17
2. what is normalization?
Basically, it's the process of efficiently organizing data in a database. There are two
goals of the normalization process: eliminate redundant data (for example, storing
the same data in more than one table) and ensure data dependencies make sense
(only storing related data in a table). Both of these are worthy goals as they reduce
the amount of space a database consumes and ensure that data is logically stored.
Well normalized data makes programming (relatively) easy, and works very well in
multi-platform, enterprise wide environments. Non-normalized data leads to heartbreak.
3. SUPPLIED PACKAGES
Several packaged procedures are provided with the Oracle Server, either to extend the
functionality of the database or to give PL/SQL access to some SQL features. You may
take advantage of the functionality provided by these packages when creating your
application, or you may simply want to use these packages for ideas in creating your own
stored procedures.
This section lists each of the supplied packages and indicates where they are described in
more detail. These packages run as the invoking user rather than the package owner. The
packaged procedures are callable through public synonyms of the same name.
20
Oracle supplies the following packaged procedures to give PL/SQL access to some
features of SQL:
• DBMS_DDL
• DBMS_SESSION
• DBMS_TRANSACTION
• DBMS_UTILITY
Table 10-3 describes each of these packages. The footnotes at the end of Table 10-3
explain any restrictions on the use of each procedure. You should consult the package
specifications for the most up-to-date information on these packages.
svpt varchar2)
(notes 1,2,4)
savepoint(savept varchar2) SAVEPOINT savepoint
(notes 1,2,4)
use_rollback_segment( SET TRANSACTION USE
rb_name varchar2) ROLLBACK SEGMENT segment
(notes 1,2,4)
purge_mixed(xid in number) See Oracle8 Server Distributed
Systems for more information
begin_discrete_transaction See the Oracle8 Server Tuning
(notes 1,3,4,5) manual for more information
local_transaction_id( See Oracle8 Server Distributed
create_transaction BOOLEAN Systems for more information
default FALSE)
return VARCHAR2
step_id return number See Oracle8 Server Distributed
Systems for more information
compile_schema(schema This procedure is equivalent to
varchar2) calling alter_compile on all
(notes 1,2,3,4) procedures, functions, and packages
accessible by you. Compilation is
completed in dependency order.
DBMS_UTILITY
analyze_schema( This procedure is equivalent to
schema varchar2, calling analyze_object on all
method varchar2, objects in the given schema.
estimate_rows number default
null,
estimate_percent number
default null)
analyze_part_object( ANALYZE TABLE | INDEX
schema in varchar2 default null, [<schema>.]<object_name>
object_name in varchar2 PARTITION <pname>
default null, [<command_type>]
object_type in char default 'T', [<command_opt>]
command_type in char [<sample_clause>]"
default 'E', for each partition of the object, run
command_opt in varchar2 in parallel using job queues. This
default null, procedure submits a job for each
sample_clause in varchar2 partition; you can control the number
default 'sample 5 percent') of concurrent jobs with the
initialization parameter
23
JOB_QUEUE_PROCESSES.
Object_type must be T (table) or I
(index). Command_type can be:
- C (compute statistics)
- E (estimate statistics)
- D (delete statistics)
- V (validate structure).
For V, command_opt can be
'CASCADE' when object_type is T.
For C or E, command_opt can be
FOR table, FOR all LOCAL
indexes, FOR all columns or a
combination of some of the 'for'
options of analyze statistics (table).
Sample_clause specifies the sample
clause to use when command_type is
E.
format_error_stack This function formats the error stack
return varchar2 into a variable.
format_call_stack This function formats the current call
return varchar2 stack into a variable.
is_parallel_server This function returns TRUE when
return boolean running in Parallel Server mode.
get_time This function returns the time in
return number hundredths of a second.
name_resolve(name in varchar2, See Oracle8 Server Distributed
DBMS_UTILITY context in number, Systems for more information.
schema out varchar2,
(continued) part1 out varchar2,
part2 out varchar2,
dblink out varchar2,
part1_type out number,
object_number out number)