Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PL SQL Interview

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 8

http://bytes.

com/topic/oracle/insights/
Using PRAGMA - I

debasi
Join Date: Dec 2006
sdas Location: Bangalore ,India
Posts: 7,611
Moderat #1 Feb 25 '08
or
PRAGMA:-Signifies that the statement is a pragma (compiler directive).
Pragmas are processed at compile time, not at run time. They pass
information to the compiler.
A pragma is an instruction to the Oracle compiler that tells it to do
something. In this case you are telling Oracle to associate an error that
you choose to a variable that you choose. This pragma must go in the
declarative section of your block.
Types of PRAGMA
1.AUTONOMOUS_TRANSACTION
2.EXCEPTION_INIT
3.RESTRICT_REFERENCES
4.SERIALLY_REUSABLE

The AUTONOMOUS_TRANSACTION pragma changes the way a


subprogram works within a transaction. A subprogram marked with this
pragma can do SQL operations and commit or roll back those
operations, without committing or rolling back the data in the main
transaction.

Just check this sample code


Expand|Select|Wrap|Line Numbers

1. CREATE OR REPLACE PROCEDURE DEPTINS


2. (
3. DNO DEPT.DEPTNO%TYPE,
4. DN DEPT.DNAME%TYPE,
5. LC DEPT.LOC%TYPE
6. )
7. AUTHID CURRENT_USER
8. IS
9. PRAGMA AUTONOMOUS_TRANSACTION;
10. BEGIN
11. INSERT INTO DEPT VALUES(DNO,DN,LC);
12. DBMS_OUTPUT.PUT_LINE('ONE ROW INSERTED......!');
13. COMMIT;
14. EXCEPTION
15. WHEN DUP_VAL_ON_INDEX THEN
16. DBMS_OUTPUT.PUT_LINE('DUPLICATE VALUE......!');
17. END;
18.

The AUTONOMOUS_TRANSACTION pragma instructs the plsql compiler


to mark a routine as autonomous (independent).An a-t is an
independent transaction started by another transaction,the main
transaction.It lets the user suspend the main transaction and all sql
operations,commit OR rollback those operations,then resume the main
transaction.

RESTRICTIONS:-
Pragma can't be used to mark all subprograms in a package as
autonomous.Only individual routines can be marked autonomous.It can
be coded any where in the declaration section of the sub program.
Once started, an autonomous transaction is fully independent.It shares
no locks,resources or commit dependencies with the main transaction.

ADVANTAGES:-
Unlike regular triggers autonomous triggers can contain COMMIT and
ROLLBACK.

Please go through this sample trigger code.


Expand|Select|Wrap|Line Numbers

1. create or replace trigger mytrig


2. before insert on emp
3. declare
4. pragma autonomous_transaction;
5. begin
6. if to_char(sysdate,'d') in(1,7) then
7. insert into trace values(user,systimestamp);
8. commit;
9. Raise_application_error(-20004,'Cannot do manipulation today');
10. end if;
11. end;
12.

Also these can execute DDL statments,using native dynamic SQL.


Expand|Select|Wrap|Line Numbers
1. create or replace trigger scotttrig
2. after logon on scott.schema
3. declare
4. pragma autonomous_transaction;
5. begin
6. if to_char(sysdate,'dy') in('sun','sat') then
7. --this is not supported in normal triggers without using PRAGMA.
8. execute immediate 'create table logtable(id varchar2(10),dt date)';
9. execute immediate 'insert into logtable values(user,sysdate)';
10. commit;
11. Raise_application_error(-20004,'Cannot do LOGIN today');
12. end if;
13. end;
14.

LIMITATIONS:-
Changes made by a-t become visible to other transaction when the a-t
commits.The changes also become visible to the main transaction when
it resumes.
If a-t attempts to access a resource held by th main transaction(which
can't resume until the a-t routine exits),a deallock can occur.In that
case,Oracle raises an exception in the a-t,If the user tries to exit an a-t
without COMMIT OR ROLLBACK ,ORACLE RAISES AN EXCEPTION,in
both the cases the transaction is rolled back if the exception goes
unhandled.

Expand|Select|Wrap|Line Numbers

1. CREATE OR REPLACE PROCEDURE


2. update_salary (dept_in IN NUMBER)
3. IS
4. PRAGMA AUTONOMOUS_TRANSACTION;
5.
6. CURSOR myemps IS
7. SELECT empno FROM emp
8. WHERE deptno = dept_in
9. FOR UPDATE NOWAIT;
10. BEGIN
11. FOR rec IN myemps
12. LOOP
13. UPDATE emp SET sal = sal * 2
14. WHERE empno = rec.empno;
15. END LOOP;
16. COMMIT;
17. END;
18. ------------
19. BEGIN
20. UPDATE emp SET sal = sal * 2;
21. update_salary (10);
22. END;
23.

Expand|Select|Wrap|Line Numbers

1. CREATE TRIGGER parts_trig


2. BEFORE INSERT ON parts FOR EACH ROW
3. DECLARE
4. PRAGMA AUTONOMOUS_TRANSACTION;
5. BEGIN
6. INSERT INTO parts_log VALUES(:new.pnum, :new.pname);
7. COMMIT;
8. END;

9.

Using PRAGMA - II

debasi
Join Date: Dec 2006
sdas Location: Bangalore ,India
Posts: 7,611
Moderat #1 Jun 16 '07
or
This thread contains some useful tips/sample codes regarding some of advance concep
oracle, that the forum members may find useful.

PRAGMA EXCEPTION_INIT
====================
This is used to bind a user defined exception to a particular error number.

For example: To display USER DEFINED MESSAGE FOR ORACLE DEFINED NUMBER
---------------------
Expand|Select|Wrap|Line Numbers

1. DECLARE
2. I EXCEPTION;
3. PRAGMA EXCEPTION_INIT(I,-00001);
4. BEGIN
5. INSERT INTO DEPT VALUES(&DNO,'&DNAME','&LOC');
6. DBMS_OUTPUT.PUT_LINE('ONE RECORD INSERTED');
7. EXCEPTION
8. WHEN I THEN
9. DBMS_OUTPUT.PUT_LINE('DUPLICATE VALUE');
10. END;
11.

Few more predefined number for predefined exception


========================================

dup_val_on_index, -0001
timeout_on_resource, -0051
invalid_cursor, -1001
not_logged_on, -1012
login_denied, -1017
too_many_rows, -1422
zero_divide, -1476
invalid_number, -1722
storage_error, -6500
program_error, -6501
value_error, -6502
rowtype_mismatch, -6504
cursor_already_open, -6511
access_into_null, -6530
collection_is_null , -6531
subscript_outside_limit, -6532
subscript_beyond_count , -6533

debasi
Join Date: Dec 2006
sdas Location: Bangalore ,India
Posts: 7,611
Moderat #2 Jun 16 '07
or
re: Using PRAGMA - II
RESTRICT_REFERENCES Pragma
===========================
This pragma was used to assert to the PL/SQL compiler the purity level of a packaged
RESTRICT_REFERENCES pragma had to be included in the package specification if you
inside a SQL statement (directly or indirectly).

This is not required starting with Oracle8i.

This pragma confirms to Oracle database that the function as the specified side-effects
such side-effects.

Usage is as follows:

PRAGMA RESTRICT_REFERENCES(function_name, WNDS [, WNPS] [, RNDS], [, RNPS]

WNDS: Writes No Database State. States that the function will not perform any DMLs.

WNPS: Writes No Package State. States that the function will not modify any Package

RNDS: Reads No Database State. Analogous to Write. This pragma affirms that the fun
database tables.

RNPS: Reads No Package State. Analogous to Write. This pragma affirms that the func
variables.

You can declare the pragma RESTRICT_REFERENCES only in a package spec or object
to four constraints (RNDS, RNPS, WNDS, WNPS) in any order. To call the function from
specify all four constraints. No constraint implies another. For example, WNPS does no

When you specify TRUST, the function body is not checked for violations of the constra
function is trusted not to violate them.

If you specify DEFAULT instead of a function name, the pragma applies to all functions
type spec (including, in the latter case, the system-defined constructor). You can still d
individual functions. Such pragmas override the default pragma.

A RESTRICT_REFERENCES pragma can apply to only one function declaration. So, a pr


name of overloaded functions always applies to the nearest foregoing function declarat

syntax
========
Expand|Select|Wrap|Line Numbers

1. PRAGMA RESTRICT_REFERENCES (
2. function_name, WNDS [, WNPS] [, RNDS] [, RNPS] [, TRUST] );
3.

In the following example, the pragma applies to the second declaration of isok:
Expand|Select|Wrap|Line Numbers

1. CREATE PACKAGE showrec AS


2. FUNCTION isok (amount NUMBER) RETURN BOOLEAN;
3. FUNCTION isok (net_time DATE) RETURN BOOLEAN;
4. PRAGMA RESTRICT_REFERENCES (isok, WNDS);
5. ...
6. END showrec;
7.

DEFAULT
----------------
This specifies that the pragma applies to all functions in the package spec or object typ
the pragma for individual functions. Such pragmas override the default pragma.
debasisdas
Moderator
re: Using PRAGMA - II
SERIALLY_REUSABLE:
====================
This pragma lets the PL/SQL engine know that package-level data should not persist be
data.

Package data (global variables in package specification etc.) by default persists for an
package is recompiled). Globally accessible data structures can cause some side effect
cursor is left open in a package. In addition, a program can use up lots of real memory
it if the data is stored in a package-level structure.

In order to manage this, Oracle8i introduced the SERIALLY_REUSABLE pragma. This pr


only and must be defined BOTH in specification and in the body. A bodiless package ca
reusable. If a package has a spec and body, you must mark both. You cannot mark on

The global memory for serially reusable packages is pooled in the System Global Area
individual users in the User Global Area (UGA). That way, the package work area can b
the server ends, the memory is returned to the pool. Each time the package is reused,
initialized to their default values or to NULL.

The advantage is that based on the pragma, a package state can be reduced to a singl
package as opposed to the package being available for the whole session.

Note :---Serially reusable packages cannot be accessed from database triggers.

SAMPLE CODE OF PRAGMA SERIALLY_REUSABLE;


===========================================
Expand|Select|Wrap|Line Numbers
1. CREATE PACKAGE pkg1 IS
2. PRAGMA SERIALLY_REUSABLE;
3. num NUMBER := 0;
4. PROCEDURE init_pkg_state(n NUMBER);
5. PROCEDURE print_pkg_state;
6. END pkg1;
7.
8. CREATE PACKAGE BODY pkg1 IS
9. PRAGMA SERIALLY_REUSABLE;
10. PROCEDURE init_pkg_state (n NUMBER) IS
11. BEGIN
12. pkg1.num := n;
13. END;
14.
15. PROCEDURE print_pkg_state IS
16. BEGIN
17. dbms_output.put_line('Number: ' || pkg1.num);
18. END;
19. END pkg1;

20.

You might also like