You are on page 1of 8

1.

Pragma
A pragma is a directive to the PL/SQL compiler. Pragmas pass information to the compiler; they are
processed at compile time but do not execute. If you include a call to a built-in package in a SQL
statement, you must include a RESTRICT REFERENCES pragma in your code. This pragma tells the
compiler the purity level (freedom from side effects) of a packaged program.
Pragma keyword is used to give instructions to the compiler. There are 4 types of Pragmas:
A) Exception_Init: - Tells the compiler to associate the specified error number with an identifier
that has been declared an Exception in your current program or an accessible package.
B) Restrict_References: - Tells the compiler the purity level of packaged program. The purity level
is the degree to which a program does not read/write database tables and/or packaged variables.
C) Serially_Reusable: - Tells the runtime engine that package data should not persist between
references. This is used to reduce per-user memory requirements when the package data is only
needed for duration of call and not the duration of session.
D) Autonomous_Transactions: - Tells the compiler that the function, procedure, top-level
anonymous P/L SQL block, object method, or database trigger executes in its own transaction
space.

Sub query and Co-relater query


Sub query is select statement which is lying in clause of
Another sql stament
Corelated subquery:
It is row-by-row processing, in which outer sub query is
processing for every inner query result

A materialized view is a database object that contains the results of a query. They are local copies of data
located remotely, or are used to create summary tables based on aggregations of a table's data. Materialized
views, which store data based on remote tables are also, know as snapshots.
The following statement creates the primary-key materialized view on the table emp located on a remote
database.
SQL> CREATE MATERIALIZED VIEW mv_emp_pk
REFRESH FAST START WITH SYSDATE
NEXT SYSDATE + 1/48
WITH PRIMARY KEY
AS SELECT * FROM emp@remote_db;
2. Top Nth Salary
Select min (sal) from EMP a
Where &N > (select count (distinct sal) from emp b where a.sal < b.sal)
Order by sal desc;
)
What are object group?
An object group is a container for a group of objects. You define an object group when you want to
package related objects so you can copy or reference them in another module
Reading.
in_file text_io.file_type;
in_file := text_io.fopen(Rtrim(:control.imp_file),'R');
loop
begin
text_io.get_line(in_file, linebuf);
if ltrim(rtrim(linebuf)) is null then exit
end;
mbenef_accno := to_number(substr(mclient_code,9,8));
text_io.fclose(in_file);
Writing
declare
outfile text_io.file_type;
filename varchar2(100);
str varchar2(100);
cursor c1 is select empno,ename from emp;
begin
filename:='d:\rashid.doc';
outfile:=text_io.fopen(filename,'w');
str:='Empno'||','||'Ename';
text_io.put_line(outfile,str);
str:='';
for i in c1
loop
str:=i.empno||','||i.ename;
text_io.put_line(outfile,str);
END LOOP;
text_io.fclose(outfile);
exception
when others then
text_io.fclose(outfile);
end;
3. Varray/Nested Table (Difference)

Varrays
 An array is an ordered set of data elements.
 All elements of a given array are of the same datatype.
 Each element has an index, which is a number corresponding to the element's position
in the array.
 specify a maximum size when you declare the array type.
CREATE OR REPLACE TYPE vcarray AS VARRAY(10) OF VARCHAR2(128);
CREATE TABLE varray_table (id number, col1 vcarray);
NSERT INTO varray_table VALUES (1, vcarray('A'));
COMMIT;
SELECT t1.id, t2.column_value
FROM varray_table t1, TABLE(t1.col1) t2;
Nested Tables
A nested table is an unordered set of data elements, all of the same datatype. It has a single
column, and the type of that column is a built-in type or an object type. If an object type, the
table can also be viewed as a multi-column table, with a column for each attribute of the
object type.
A table type definition does not allocate space. It defines a type, which you can use as
CREATE OR REPLACE TYPE CourseList AS TABLE OF VARCHAR2(64);
CREATE TABLE department (
name     VARCHAR2(20),
director VARCHAR2(20),
office   VARCHAR2(20),
courses  CourseList)
NESTED TABLE courses STORE AS courses_tab

Differences between Nested Tables and Varrays

Nested tables differ from varrays in the following ways:


 Varrays have a maximum size, but nested tables do not.
 Varrays are always dense, but nested tables can be sparse. So, you can delete individual
elements from a nested table but not from a varray.
4. Select even row from emp table
Select * from EMP where rowid in (select decode (mod (rownum, 2), 0,rowid, null) from emp);
5. Select odd row from emp table
Select * from EMP where rowid in (select decode (mod (rownum, 2), 1,rowid, null) from emp);
6. Select Nth row from emp table where N=10
Select * from EMP where rowid=(select rowid from EMP where ROWNUM <= 10
MINUS
Select rowid from EMP where ROWNUM < 10)
7. Select rows X to Y from emp table where X=5 and Y=7
Select * from EMP where rowid in (select rowid from EMP
Where rowNUM <= 7
MINUS
Select rowid from EMP where rownum < 5);
8. All even, Odd, Nth rows from a table
Select * from emp where (rowid, 0) in (select rowid, mod (rownum,&n) from emp);
9. Select N rows from a table
Select * from EMP a
Where &n>(select count (distinct (sal)) from emp b where a. Sal >= b.sal)
Order by sal desc;
10. Select Employee having maximum salary in department from emp table
Select deptno, empno, sal from EMP a where (deptno, sal) in (
Select deptno, max (sal) from EMP b
Where a.deptno = b.deptno
Group by b.deptno) order by 1
For the second lowest salary:
select level, min(sal) from emp
where level=2
connect by prior sal < sal
group by level
REF CURSOR?
Ref cursor is a cursor variable which acts as a pointer to
the sql memory area.
Ref cursor can be asssociated with multiple sql statements
where as a cursor can be associated with only one sql
statement.
Refcursor is dynamic where as cursor is static.
Ref cursors are of two types:
1)strong ref cursor:which retuns value.
2)week ref cursor:which doesn't return value
CREATE OR REPLACE PROCEDURE sptest
RETURN types.ref_cursor
AS
types.ref_cursor IS REF CURSOR;
BEGIN
OPEN types.ref_cursor FOR
SELECT ES.EMPLOYEE_NUMBER, ES.NAME
FROM CPC1.EMPLOYEE_SNAPSHOT_CPC ES;

RETURN types.ref_cursor;
END;
TABLE my_temp_table (
Global Temproary Table.

The data in a global temporary table is private, such that data inserted by a session can only be accessed by
that session. The session-specific rows in a global temporary table can be preserved for the whole session, or
just for the current transaction. The ON COMMIT DELETE ROWS clause indicates that the data should be
deleted at the end of the transaction.
column1 NUMBER,
column2 NUMBER
) ON COMMIT DELETE ROWS;
In contrast, the ON COMMIT PRESERVE ROWS clause indicates that rows should be preserved until the end of
the In contrast, the ON COMMIT PRESERVE ROWS clause indicates that rows should be preserved until the
end of the session.

CREATE GLOBAL TEMPORARY TABLE my_temp_table (


column1 NUMBER,
column2 NUMBER
) ON COMMIT PRESERVE ROWS;

----------------------There will be 12 type of trigger.

1) BEFORE INSERT STATEMENT LEVEL


2) BEFORE INSERT ROW LEVEL
3) BEFORE UPDATE STATEMENT LEVEL
4) BEFORE UPDATE ROW LEVEL
5) BEFORE DELETE STATEMENT LEVEL
6) BEFORE DELETE ROW LEVEL
7) AFTER INSERT STATEMENT LEVEL
8) AFTER INSERT ROW LEVEL
9) AFTER UPDATE STATEMENT LEVEL
10)AFTER UPDATE ROW LEVEL
11)AFTER DELETE STATEMENT LEVEL
12)AFTER DELETE ROW LEVEL
Autonomous Transaction is a feature of oracle 8i which maintains the state of its transactions and
save it , to affect with the commit or rollback of the surrounding transactions.
Here is the simple example to understand this :-
SamSQL :> declare
2 Procedure InsertInTest_Table_B
3 is
4 BEGIN
5 INSERT into Test_Table_B(x) values (1);
6 Commit;
7 END ;
8 BEGIN
9 INSERT INTO Test_Table_A(x) values (123);
10 -- InsertInTest_Table_B;
11 Rollback;
12 END;
13 /
 PL/SQL procedure successfully completed.
 ora816 SamSQL :> Select * from Test_Table_A;
X
----------
123
ora816 SamSQL :> Select * from Test_Table_B;
X
----------
1
 
Notice in above pl/sql COMMIT at line no 6 , commits the transaction at line-no 5 and line-
no 9. The Rollback at line-no 11 actually did nothing. Commit/ROLLBACK at nested
transactions will commit/rollback all other DML transaction before that. PRAGMA
AUTONOMOUS_TRANSACTION override this behavior.
Let us the see the following example with PRAGMA AUTONOMOUS_TRANSACTION.
 ora816 SamSQL :> declare
2 Procedure InsertInTest_Table_B
3 is
4 PRAGMA AUTONOMOUS_TRANSACTION;
5 BEGIN
6 INSERT into Test_Table_B(x) values (1);
7 Commit;
8 END ;
9 BEGIN
10 INSERT INTO Test_Table_A(x) values (123);
11 InsertInTest_Table_B;
12 Rollback;
13 END;
14 /
 
PL/SQL procedure successfully completed.
ora816 SamSQL :> Select * from Test_Table_A;
no rows selected
ora816 SamSQL :> Select * from Test_Table_B;
 
X
----------
1
 
With PRAGMA AUTONOMOUS_TRANSACTION , the transaction state maintained
independently . Commit/Rollback of nested transaction will no effect the other transaction.
It is advisable to increase the value of TRANSACTIONS parameter in the INIT parameter
file to allow for the extra concurrent transaction

Use of commit inside trigger-


CREATE OR REPLACE TRIGGER TUA_TEST
AFTER UPDATE OF COL3
ON TEST
FOR EACH ROW
BEGIN
INSERT INTO audit_test(col1,col2,new_col3,old_col3,col4)
VALUES(: old.col1, : old.col2, : new.col3, : old.col3,sysdate);
COMMIT;
END;
/

Trigger will get created without any error. But whenever we update test table, we run into
following error.

SQL> UPDATE TEST


2  SET COL3 = 2000
3  WHERE col1 = 1;
UPDATE TEST
*
ERROR at line 1:
ORA-04092: cannot COMMIT in a trigger
ORA-06512: at “SCOTT.TUA_TEST”, line 5
ORA-04088: error during execution of trigger ‘SCOTT.TUA_TEST’

Now let us create same trigger with pragma autonomous_transaction and execute the update
statement again.

CREATE OR REPLACE TRIGGER TUA_TEST


AFTER UPDATE OF COL3
ON TEST
FOR EACH ROW
DECLARE
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
INSERT INTO audit_test(col1,col2,new_col3,old_col3,col4)
VALUES(: old.col1, : old.col2, :new.col3, : old.col3,sysdate);

COMMIT;

END;

BULK COLLECT

I have started using BULK COLLECT whenever I need to fetch large volumes of data. This has caused me
some trouble with my DBA, however. He is complaining that although my programs might be running much
faster

Code Listing 1: Using BULK COLLECT with LIMIT clause


PROCEDURE process_all_rows (limit_in IN PLS_INTEGER DEFAULT 100)
IS
CURSOR employees_cur
IS
SELECT * FROM employees;
TYPE employees_aat IS TABLE OF employees_cur%ROWTYPE
INDEX BY PLS_INTEGER;
l_employees employees_aat;
BEGIN
OPEN employees_cur;
LOOP
FETCH employees_cur
BULK COLLECT INTO l_employees LIMIT limit_in;
FOR indx IN 1 .. l_employees.COUNT
LOOP
analyze_compensation (l_employees(indx));
END LOOP;
EXIT WHEN l_employees.COUNT < limit_in;
END LOOP;
CLOSE employees_cur;
END process_all_rows;

BULK COLLECT – UPDATE - FORALL

DECLARE
TYPE prod_id_tab is TABLE OF products.product_id%TYPE;
TYPE prod_tab IS TABLE OF products%ROWTYPE;
products_id_tab prod_id_tab := prod_id_tab();
products_tab prod_tab := prod_tab();
start_time number;
end_time number;
BEGIN
-- Populate a collection - 10000 rows
FOR i in 1 .. 10000 LOOP
products_id_tab.extend;
products_id_tab(products_id_tab.last) := i+10;

products_tab.extend;
products_tab(products_tab.last).product_id := i;
END LOOP;

Start_time := DBMS_UTILITY.get_time;
FOR i in products_tab.first .. products_tab.last LOOP
UPDATE products SET ROW = products_tab(i) -- ROW available in 9.2
WHERE product_id = products_tab(i).product_id;
END LOOP;
end_time := DBMS_UTILITY.get_time;
DBMS_OUTPUT.PUT_LINE('Conventional Update: '||to_char(end_time-start_time));

Start_time := DBMS_UTILITY.get_time;
FORALL i in products_tab.first .. products_tab.last
UPDATE products SET ROW = products_tab(i) – ROW available in 9.2
WHERE product_id = products_id_tab(i);
end_time := DBMS_UTILITY.get_time;
DBMS_OUTPUT.PUT_LINE('Bulk Update: '||to_char(end_time-start_time));
END;
Data may be Bulk Collected/Fetched into:
Table.column%TYPE
Record of arrays
Table%ROWTYPE
Cursor%ROWTYPE
Array of records
Nested tables
BULK COLLECT – Explicit Cursor- LIMIT
DECLARE
TYPE prod_tab IS TABLE OF products%ROWTYPE;
products_tab prod_tab := prod_tab();
start_time number;
end_time number;
CURSOR products_data IS SELECT * FROM products;
BEGIN
Start_time := DBMS_UTILITY.get_time;
OPEN products_data;
LOOP
FETCH products_data BULK COLLECT INTO products_tab LIMIT 10000;
EXIT WHEN products_data%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('Processed '||to_char(products_tab.count)||' rows');
END LOOP;
CLOSE products_data;
end_time := DBMS_UTILITY.get_time;
DBMS_OUTPUT.PUT_LINE('Bulk Collect: ‘||to_char(end_time-start_time));

Reading.

declare
infile text_io.file_type;
linebuf varchar2(5000);
begin
in_file := text_io.fopen(Rtrim(:control.imp_file),'R');
loop
text_io.get_line(in_file, linebuf);
end loop;
text_io.`(in_file);
end;

-You cannot specify the WHEN clause for INSTEAD OF triggers.


-The size of a trigger cannot be more than 32K.

Creation of Global Temporary Tables


The data in a global temporary table is private, such that data inserted by a session can only be
accessed by that session. The session-specific rows in a global temporary table can be preserved
for the whole session, or just for the current transaction. The ON COMMIT DELETE ROWS clause
indicates that the data should be deleted at the end of the transaction.
CREATE GLOBAL TEMPORARY TABLE my_temp_table (
column1 NUMBER,
column2 NUMBER
) ON COMMIT DELETE ROWS;
In contrast, the ON COMMIT PRESERVE ROWS clause indicates that rows should be preserved until
the end of the session.
CREATE GLOBAL TEMPORARY TABLE my_temp_table (
column1 NUMBER,
column2 NUMBER
) ON COMMIT PRESERVE ROWS;

Miscellaneous Features
• If the TRUNCATE statement is issued against a temporary table, only the session specific
data is trucated. There is no affect on the data of other sessions.
• Data in temporary tables is automatically delete at the end of the database session, even if
it ends abnormally.
• Indexes can be created on temporary tables. The content of the index and the scope of the
index is that same as the database session.
• Views can be created against temporary tables and combinations of temporary and
permanent tables.
• Temporary tables can have triggers associated with them.
• Export and Import utilities can be used to transfer the table definitions, but no data rows
are processed.
• There are a number of restrictions related to temporary tables but these are version
specific.

A stored procedure, function, or package is a PL/SQL program unit that:


Has a name.
Can take parameters, and can return values.
Is stored in the data dictionary.
Can be called by many users.
Note:
The term stored procedure is sometimes used generically for both stored procedures
and stored functions. The only difference between procedures and functions is that
functions always return a single value to the caller, while procedures do not return a
value to the caller
Note:
Numerically constrained types such as NUMBER(2) or VARCHAR2(20) are
not allowed in a parameter list.

16) What are OPEN_FORM,CALL_FORM,NEW_FORM? Diff?


16) CALL_FORM : It calls the other form. but parent remains active, when called form completes the
operation , it releases lock and control goes back to the calling form.
When you call a form, Oracle Forms issues a savepoint for the called form. If the CLEAR_FORM function
causes a rollback when the called form is current, Oracle Forms rolls back uncommitted changes to this
savepoint.
OPEN_FORM : When you call a form, Oracle Forms issues a savepoint for the called form. If the
CLEAR_FORM function causes a rollback when the called form is current, Oracle Forms rolls back
uncommitted changes to this savepoint.
NEW_FORM : Exits the current form and enters the indicated form. The calling form is terminated as
the parent form. If the calling form had been called by a higher form, Oracle Forms keeps the higher call
active and treats it as a call to the new form. Oracle Forms releases memory (such as database cursors)
that the terminated form was using.
Oracle Forms runs the new form with the same Runform options as the parent form. If the parent form was
a called form, Oracle Forms runs the new form with the same options as the parent form

----------
Form

1. Forms won't allow me to use restricted built-in's.What should I do?

Answer: How to get around the "can't use a restricted built-in in built-in XXX" message:
1. Create a TIMER at the point where you want the navigation to
occur.Eg.create_timer('TIMER_X', 5, NO_REPEAT);
2. Code a WHEN-TIMER-EXPIRED trigger to handle the navigation

DECLARE
tm_name VARCHAR2(20);
BEGIN
tm_name := Get_Application_Property(TIMER_NAME);
IF tm_name = 'TIMER_X' THEN
Go_Item('ITEM_X');
END IF;
END;

Delete all rowids that is BIGGER than the SMALLEST rowid value (for a given key):

SQL> DELETE FROM table_name A WHERE ROWID > (


2 SELECT min(rowid) FROM table_name B
3 WHERE A.key_values = B.key_values);

You might also like