SQL Note
SQL Note
PL/SQL stands for Procedural Language/SQL.PL/SQL extends SQL by adding control Structures found in
other procedural language.PL/SQL combines the flexibility of SQL with Powerful feature of 3 rd
generation Language. The procedural construct and database access Are present in PL/SQL.PL/SQL can
be used in both in database in Oracle Server and in Client side application development tools.
Advantages of PL/SQL
Support for SQL, support for object-oriented programming,, better performance, portability, higher
productivity, Integration with Oracle
a] Supports the declaration and manipulation of object types and collections.
b] Allows the calling of external functions and procedures.
c] Contains new libraries of built in packages.
d] with PL/SQL , an multiple sql statements can be processed in a single command line statement.
PL/SQL Datatypes
Scalar Types
BINARY_INTEGER ,DEC,DECIMAL,DOUBLE ,,PRECISION,FLOAT,INT,INTEGER,NATURAL,
NATURALN,NUMBER, NUMERIC, PLS_INTEGER,POSITIVE,POSITIVEN,REAL,SIGNTYPE,
SMALLINT,CHAR,CHARACTER,LONG,LONG RAW,NCHAR,NVARCHAR2,RAW,ROWID,STRING,
VARCHAR,VARCHAR2,
Composite Types
TABLE, VARRAY, RECORD
LOB Types
BFILE, BLOB, CLOB, NCLOB
Reference Types
REF CURSOR
BOOLEAN, DATE
DBMS_OUTPUT.PUT_LINE:
It is a pre-defined package that prints the message inside the parenthesis
ANONYMOUS PL/SQL BLOCK.
The text of an Oracle Forms trigger is an anonymous PL/SQL block. It consists of three sections:
A declaration of variables, constants, cursors and exceptions which is optional.
A section of executable statements.
A section of exception handlers, which is optional.
ATTRIBUTES
Allow us to refer to data types and objects from the database.PL/SQL variables and Constants can have
attributes. The main advantage of using Attributes is even if you Change the data definition, you dont
need to change in the application.
%TYPE
It is used when declaring variables that refer to the database columns.
Using %TYPE to declare variable has two advantages. First, you need not know the exact datatype of
variable. Second, if the database definition of variable changes, the datatype of variable changes
accordingly at run time.
1
%ROWTYPE
The %ROWTYPE attribute provides a record type that represents a row in a table (or view). The record
can store an entire row of data selected from the table or fetched from a cursor or strongly typed
cursor variable.
EXCEPTION
An Exception is raised when an error occurs. In case of an error then normal execution stops and the
control is immediately transferred to the exception handling part of the PL/SQL Block.
Exceptions are designed for runtime handling, rather than compile time handling. Exceptions improve
readability by letting you isolate error-handling routines.
When an error occurs, an exception is raised. That is, normal execution stops and control transfers to
the exception-handling part of your PL/SQL block or subprogram. Internal exceptions are raised
implicitly (automatically) by the runtime system. User-defined exceptions must be raised explicitly by
RAISE statements, which can also raise predefined exceptions.
To handle raised exceptions, you write separate routines called exception handlers. After an exception
handler runs, the current block stops executing and the enclosing block resumes with the next
statement. If there is no enclosing block, control returns to the host environment.
Exception Types
1. Predefined Exceptions
An internal exception is raised implicitly whenever your PL/SQL program violates an Oracle rule or
exceeds a system-dependent limit. Every Oracle error has a number, but exceptions must be handled
by name. So, PL/SQL predefines some common Oracle errors as exceptions. For example, PL/SQL
raises the predefined exception NO_DATA_FOUND if a SELECT INTO statement returns no rows.
2. User Defined exceptions
User defined exception must be defined and explicitly raised by the user
EXCEPTION_INIT
A named exception can be associated with a particular oracle error. This can be used to trap the error
specifically.
PRAGMA EXCEPTION_INIT(exception name, Oracle_error_number);
The pragma EXCEPTION_INIT associates an exception name with an Oracle, error number. That allows
you to refer to any internal exception by name and to write a specific handler
RAISE_APPLICATION_ERROR
The procedure raise_application_error lets you issue user-defined error messages from stored
subprograms. That way, you can report errors to your application and avoid returning unhandled
exceptions.
To call raise_application_error, you use the syntax
raise_application_error(error_number, message[, {TRUE | FALSE}]);
where error_number is a negative integer in the range -20000 .. -20999 and message is a character
string up to 2048 bytes long.
Declare a cursor
Open a cursor
Fetch data from the cursor
Close the cursor
END LOOP;
To refer an element of the record use <record name. Column name>
Parameterized Cursor
A cursor can take parameters, which can appear in the associated query wherever constants can
appear. The formal parameters of a cursor must be IN parameters. Therefore, they cannot return
values to actual parameters. Also, you cannot impose the constraint NOT NULL on a cursor parameter.
The values of cursor parameters are used by the associated query when the cursor is opened.
B .IMPLICIT CURSOR
An IMPLICIT cursor is associated with any SQL DML statement that does not have a explicit
cursor associated with it.
This includes:
All
All
All
All
INSERT statements
UPDATE statements
DELETE statements
SELECT .. INTO statements
ORACLE 9I
Advanced Explicit Cursor Concepts
1. FOR UPDATE WAIT Clause
Syntax
Cursor eipc1 is select * from emp for update [ of column_reference ] [ NOWAIT ]
Column Reference
NOWAIT
The SELECT... FOR UPDATE statement has been modified to allow the user to specify how
long the command should wait if the rows being selected are locked.
If NOWAIT is specified, then an error is returned immediately if the lock cannot be obtained.
Example of Using FOR UPDATE WAIT Clause
1. SELECT * FROM EMPLOYEES WHERE DEPARTMENT_ID = 10 FOR UPDATE WAIT 20;
2. DECLARE
CURSOR EMP_CURSOR IS
SELECT EMPNO, ENAME, DNAME FROM EMP,DEPT WHERE
EMP.DEPTNO=DEPT.DEPTNO AND EMP.DEPTNONO=80
FOR UPDATE OF SALARY NOWAIT;
[ Retrieve the Employees who work in department 80 and update their Salary ]
2. The WHERE CURRENT OF Clause
Syntax
END IF;
END LOOP;
END;
[The Example loops through each employee in department 80 , and checks whether the salary is
less than 5000.If salary is less than , the salary is raised by 10%. The where current of clause in the
UPDATE statement refers to the currently fetched records. ]
3. CURSORS WITH SUB QUERIES
Sub queries are often used in the WHERE clause of select statement. It can be used to
FROM clause, creating a temporary data source for the query.
DECLARE
bonus REAL;
BEGIN
FOR emp_rec IN (SELECT empno, sal, comm FROM emp)
LOOP
bonus := (emp_rec.sal * 0.05) + (emp_rec.comm * 0.25);
INSERT INTO bonuses VALUES (emp_rec.empno, bonus);
END;
END LOOP;
COMMIT;
PROCEDURES
Procedure is a subprogram that contains set of SQL and PL/SQL statements.
Merits
END;
9 PROCEDURE do_nothing1 (tab IN OUT EmpTabTyp) IS
10
BEGIN
NULL;
END;
11 PROCEDURE do_nothing2 (tab IN OUT NOCOPY EmpTabTyp) IS
12
BEGIN
NULL;
END;
13 BEGIN
14
SELECT * INTO emp_tab(1) FROM emp WHERE empno = 7788;
15
emp_tab.EXTEND(24999, 1); -- copy element 1 into 2..25000
16
get_time(t1);
17
do_nothing1(emp_tab); -- pass IN OUT parameter
18
get_time(t2);
19
do_nothing2(emp_tab); -- pass IN OUT NOCOPY parameter
20
get_time(t3);
21
DBMS_OUTPUT.PUT_LINE(Call Duration (secs));
22
DBMS_OUTPUT.PUT_LINE(--------------------);
23
DBMS_OUTPUT.PUT_LINE(Just IN OUT: || TO_CHAR(t2 - t1));
24
DBMS_OUTPUT.PUT_LINE(With NOCOPY: || TO_CHAR(t3 - t2));
25* END;
SQL> /
Call Duration (secs)
-------------------Just IN OUT: 21
With NOCOPY: 0
Autonomous Transactions
A transaction is a series of SQL statements that does a logical unit of work. Often, one transaction
starts another. In some applications, a transaction must operate outside the scope of the transaction
that started it. This can happen, for example, when a transaction calls out to a data cartridge.
An autonomous transaction is an independent transaction started by another transaction, the main
transaction. Autonomous transactions let you suspend the main transaction, do SQL operations,
commit or roll back those operations, then resume the main transaction.
Advantages of Autonomous Transactions
Once started, an autonomous transaction is fully independent. It shares no locks, resources, or
commit-dependencies with the main transaction. So, you can log events, increment retry counters, and
so on, even if the main transaction rolls back.
More important, autonomous transactions help you build modular, reusable software components. For
example, stored procedures can start and finish autonomous transactions on their own. A calling
application need not know about a procedures autonomous operations, and the procedure need not
know about the applications transaction context. That makes autonomous transactions less
Error-prone than regular transactions and easier to use.
Furthermore, autonomous transactions have all the functionality of regular transactions. They allow
parallel queries, distributed processing, and all the transaction control statements including SET
TRANSACTION.
VIEW SOURCE CODE FOR PROCEDURES
SELECT TEXT FROM USER_SOURCE WHERE NAME='&P1' AND TYPE=PROCEDURE
FUNCTIONS
Function is a subprogram that computes and returns a single value.
A function is a subprogram that computes a value. Functions and procedures are structured alike,
except that functions have a RETURN clause.
FUNCTION NAME [(PARAMETER[, PARAMETER, ...])] RETURN DATATYPE IS
[LOCAL DECLARATIONS]
BEGIN
EXECUTABLE STATEMENTS
[EXCEPTION
EXCEPTION HANDLERS]
A function has two parts: the specification and the body. The function specification begins with the
keyword FUNCTION and ends with the RETURN clause, which specifies the datatype of the result value.
Parameter declarations are optional. Functions that take no parameters are written without
parentheses. The function body begins with the keyword IS and ends with the keyword END followed
by an optional function name.
Using the RETURN Statement
The RETURN statement immediately completes the execution of a subprogram and returns control to
the caller. Execution then resumes with the statement following the subprogram call. (Do not confuse
the RETURN statement with the RETURN clause in a function spec, which specifies the datatype of the
return value.)
A subprogram can contain several RETURN statements, none of which need be the last lexical
statement. Executing any of them completes the subprogram immediately. However, to have multiple
exit points in a subprogram is a poor programming practice.
In procedures, a RETURN statement cannot contain an expression. The statement simply returns
control to the caller before the normal end of the procedure is reached.
However, in functions, a RETURN statement must contain an expression, which is evaluated when the
RETURN statement is executed. The resulting value is assigned to the function identifier, which acts like
a variable of the type specified in the RETURN clause. Observe how the function balance returns the
balance of a specified bank account:
COMPARING PROCEDURES AND FUNCTIONS
Procedure
Function
No RETURN datatype
Improved performance
Avoid reparsing for multiple users by exploiting the shared SQL area
Avoid PL/SQL parsing at run-time by parsing at compile time
Reduce the number of calls to the database and decrease network traffic by bundling commands
Improved maintenance.
Modify routines online without interfering with other users
Modify one routine to affect multiple applications
Modify one routine to eliminate duplicate testing
Improved data security and integrity
Control indirect access to database objects from non privileged users with security privileges
Ensure that related actions are performed together, or not at all, by funneling activity for related tables
through a single path
LIST ALL PROCEDURES AND FUNCTIONS
WHERE
OBJECT_TYPE
IN
SELECT TEXT
FROM USER_SOURCE
ORDER BY LINE;
PACKAGE
A package is a schema object that groups logically related PL/SQL types, items, and subprograms.
Packages usually have two parts, a specification and a body,
Merits
Simplify security
Limit recompilation
Performance
Information Hiding
Hiding
Parts of Package
A.PACKAGE SPECIFICATION
The package specification contains public declarations. The scope of these declarations is local to your
database schema and global to the package. So, the declared items are accessible from your
application and from anywhere in the package.
B.PACKAGE BODY
The package body implements the package specification. That is, the package body contains the
definition of every cursor and subprogram declared in the package specification. Keep in mind that
subprograms defined in a package body are accessible outside the package only if their specifications
also appear in the package specification.
PACKAGE OVERLOADING
PL/SQL allows two or more packaged subprograms to have the same name. This option is useful when
you want a subprogram to accept parameters that have different datatypes.
PRIVATE VERSUS PUBLIC ITEMS
PRIVATE
The package body can also contain private declarations, which define types and items necessary for the
internal workings of the package. The scope of these declarations is local to the package body.
11
Therefore, the declared types and items are inaccessible except from within the package body. Unlike a
package spec, the declarative part of a package body can contain subprogram bodies.
PUBLIC
Such items are termed public. When you must maintain items throughout a session or across
transactions, place them in the declarative part of the package body.
Advantages of Packages
Packages offer several advantages: modularity, easier application design, information hiding, added
functionality, and better performance.
Modularity
Packages let you encapsulate logically related types, items, and subprograms in a named
PL/SQL module. Each package is easy to understand, and the interfaces between packages are
simple, clear, and well defined. This aids application development.
Information Hiding
With packages, you can specify which types, items, and subprograms are public (visible and
accessible) or private (hidden and inaccessible). For example, if a package contains four
subprograms, three might be public and one private. The package hides the implementation of
the private subprogram so that only the package (not your application) is affected if the
implementation changes. This simplifies maintenance and enhancement. Also, by hiding
implementation details from users, you protect the integrity of the package.
Added Functionality
Packaged public variables and cursors persist for the duration of a session. So, they can be
shared by all subprograms that execute in the environment. Also, they allow you to maintain
data across transactions without having to store it in the database.
Better Performance
When you call a packaged subprogram for the first time, the whole package is loaded into
memory. So, later calls to related subprograms in the package require no disk I/O. Also,
packages stop cascading dependencies and thereby avoid unnecessary recompiling. For
example, if you change the implementation of a packaged function, Oracle need not recompile
the calling subprograms because they do not depend on the package body.
12
The global memory for such packages is pooled in the System Global Area (SGA), not allocated to
individual users in the User Global Area (UGA). That way, the package work area can be reused. When
the call to the server ends, the memory is returned to the pool. Each time the package is reused, its
public variables are initialized to their default values or to NULL.
The maximum number of work areas needed for a package is the number of concurrent users of that
package, which is usually much smaller than the number of logged-on users. The increased use of SGA
memory is more than offset by the decreased use of UGA memory. Also, Oracle ages-out work areas
not in use if it needs to reclaim SGA memory.
For bodiless packages, you code the pragma in the package spec using the following syntax:
PRAGMA SERIALLY_REUSABLE;
For packages with a body, you must code the pragma in the spec and body. You cannot code the
pragma only in the body. The following example shows how a public variable in a serially reusable
package behaves across call boundaries:
CREATE PACKAGE pkg1 IS
PRAGMA SERIALLY_REUSABLE;
num NUMBER := 0;
PROCEDURE init_pkg_state(n NUMBER);
PROCEDURE print_pkg_state;
END pkg1;
13
DATABASE TRIGGERS
A Trigger defines an action the database should take when some database related event occurs. Triggers may be
used to supplement declarative referential integrity, to enforce complex business rules.
A database trigger is a stored subprogram associated with a table. You can have Oracle automatically fire the trigger
before or after an INSERT, UPDATE, or DELETE statement affects the table.
Triggers are executed when a specific data manipulation command are performed on specific tables
ROW LEVEL TRIGGERS
Row Level triggers execute once for each row in a transaction. Row level triggers are create using FOR EACH ROW
clause in the create trigger command.
STATEMENT LEVEL TRIGGERS
Statement Level triggers execute once for each transaction. For example if you insert 100 rows in a single transaction
then statement level trigger will be executed once.
BEFORE and AFTER Triggers
Since triggers occur because of events, they may be set to occur immediately before or after those events.
The following table shows the number of triggers that you can have for a table. The number of triggers you can have a
for a table is 14 triggers.
The following table shows the number of triggers that you can have for a table. The number of triggers you can have a
for a table is 14 triggers.
BEFORE
INSERT
INSERT
UPDATE
UPDATE
DELETE
DELETE
INSTEAD OF
INSTEAD OF ROW
AFTER
INSERT
INSERT
UPDATE
UPDATE
DELETE
DELETE
ADVANTAGES OF TRIGGERS
14
Feature
Enhancement
Security
The Oracle Server allows table access to users or roles. Triggers allow table access
according to data values.
Auditing
The Oracle Server tracks data operations on tables. Triggers track values for data
operations on tables.
Data integrity
The Oracle Server enforces integrity constraints. Triggers implement complex integrity
rules.
Referential integrity
The Oracle Server enforces standard referential integrity rules. Triggers implement
nonstandard functionality.
Table replication
The Oracle Server copies tables asynchronously into snapshots. Triggers copy tables
Synchronously into replicas.
Derived data
The Oracle Server computes derived data values manually. Triggers compute derived data
values automatically.
Event logging
The Oracle Server logs events explicitly. Triggers log events transparently.
Syntax:
BEGIN
END;
Example 1:
CREATE OR REPLACE TRIGGER MY_TRIG BEFORE INSERT OR UPDATE OR DELETE ON
DETAIL FOR EACH ROW
BEGIN
IF LTRIM(RTRIM(TO_CHAR(SYSDATE,'DAY')))='FRIDAY' THEN
IF INSERTING THEN
RAISE_APPLICATION_ERROR(-20001,'INSERT IS NOT POSSIBLE');
ELSIF UPDATING THEN
RAISE_APPLICATION_ERROR(-20001,'UPDATE IS NOT POSSIBLE');
ELSIF DELETING THEN
RAISE_APPLICATION_ERROR(-20001,'DELETE IS NOT POSSIBLE');
END IF;
END IF;
END;
Example 2:
CREATE OR REPLACE TRIGGER MY_TRIG AFTER INSERT ON
ITEM FOR EACH ROW
15
FOR
DECLARE
MITEMID NUMBER;
MQTY NUMBER;
BEGIN
SELECT ITEMID INTO MITEMID FROM STOCK WHERE ITEMID = :NEW.ITEMID;
UPDATE STOCK SET QTY=QTY+:NEW.QTY WHERE ITEMID=:NEW.ITEMID;
EXCEPTION WHEN NO_DATA_FOUND THEN
INSERT INTO STOCK VALUES (:NEW.ITEMID, :NEW.QTY);
END;
Example 3:
CREATE OR REPLACE TRIGGER MY_TRIG AFTER DELETE ON
EMP FOR EACH ROW
BEGIN
INSERT INTO EMP_BACK VALUES (:OLD.EMPNO, :OLD.ENAME, :OLD.SAL, :OLD.DEPTNO);
END;
Example 4:
CREATE OR REPLACE TRIGGER TR02 BEFORE INSERT OR UPDATE OR DELETE ON EMP100
DECLARE
D1 VARCHAR(3);
BEGIN
D1:=TO_CHAR(SYSDATE,'DY');
END;
IF D1 IN('TUE','MON') THEN
RAISE_APPLICATION_ERROR(-20025,'TRY ON ANOTHER DAY');
END IF;
Example 5:
CREATE OR REPLACE TRIGGER TR01 AFTER DELETE ON DEPT200 FOR EACH ROW
BEGIN
INSERT INTO DEPT1 VALUES (:OLD.DEPTNO,:OLD.DNAME,:OLD.LOC);
END;
/
SHOW ERR
Example 6:
CREATE OR REPLACE TRIGGER TR03 AFTER UPDATE ON EMP FOR EACH ROW
BEGIN
UPDATE EMP100 SET SAL=:OLD.SAL*2 WHERE EMPNO=:OLD.EMPNO;
END;
/
SHOW ERR
Example 7:
16
EMP100
SYSTEM TRIGGER
LOGON and LOGOFF Trigger Example
You can create this trigger to monitor how often you log on and off, or you may want to write a report on how long you
are logged on for. If you were a DBA wanting to do this, you would replace SCHEMA with DATABASE.
1.
2.
CALL STATEMENT
This allows you to call a stored procedure, rather than coding the PL/SQL body in the trigger itself.
INSTEAD OF triggers to tell ORACLE what to do instead of performing the actions that executed
the trigger. An INSTEAD OF trigger can be used for a view. These triggers can be used to overcome the
restrictions placed by oracle on any view which is non updateable.
Example:
CREATE OR REPLACE VIEW EMP_DEPT AS SELECT A.DEPTNO,B.EMPNO FROM DEPT A,EMP B
WHERE A.DEPTNO=B.DEPTNO
CREATE OR REPLACE TRIGGER TRIG1 INSTEAD OF INSERT ON EMP_DEPT
REFERENCING NEW AS N FOR EACH ROW
BEGIN
INSERT INTO DEPT VALUES(:N.DEPTNO,'DNAME');
INSERT INTO EMP VALUES(:N.EMPNO,'ENAME',:N.DEPTNO);
END;
18