Thursday, 21 June 2018

Executing a DB package at Bean with a return value by using HashMap

Executing a package with a return value.


    public HashMap getProductPrice(String compcode, String unitcode, String prodCode, Date invDate) {
        BindingContext bindingContext = BindingContext.getCurrent();
        DCDataControl dc = bindingContext.findDataControl("AppModuleAMDataControl");
        AppModuleAMImpl appM = (AppModuleAMImpl)dc.getDataProvider();
        System.out.println("**Price from ValueChange:"+compcode+" "+unitcode+" prodCode:"+prodCode);

        String sqlproc2 = "{? = call Pos_Inv_Validation_Pkg.Get_Price(?,?,?,sysdate,?,?)}";
        //pi_vchno_pkg.get_pr_vchno
        CallableStatement sqlProcStmt2 = appM.getDBTransaction().createCallableStatement(sqlproc2, 0);
        HashMap hm = new HashMap<String, Object>();

        try {
            sqlProcStmt2.registerOutParameter(1, Types.VARCHAR);
            sqlProcStmt2.setString(2, compcode);
            sqlProcStmt2.setString(3, unitcode);
            sqlProcStmt2.setString(4, prodCode);
            //sqlProcStmt2.setDate(5, invDate.dateValue());
            sqlProcStmt2.registerOutParameter(5, java.sql.Types.VARCHAR);
            sqlProcStmt2.registerOutParameter(6, java.sql.Types.INTEGER);
            sqlProcStmt2.execute();

            BigDecimal v_ret_val = sqlProcStmt2.getBigDecimal(1);
            String priceType = sqlProcStmt2.getString(5);
            BigDecimal priceCntrlNo = sqlProcStmt2.getBigDecimal(6);
            hm.put("price", v_ret_val);
            hm.put("priceType", priceType);
            hm.put("priceCntrlNo", priceCntrlNo);

            System.out.println("v_ret_val " + v_ret_val+" --Date: "+invDate.dateValue()+" priceCntrlNo :"+priceCntrlNo+":priceType"+priceType);


        } catch (SQLException e) {

            System.out.println(e.getMessage());
        }

        return hm;
    }

Sunday, 17 June 2018

Difference between 10g, 11g and 12c

Difference between 10g, 11g and 12c

Oracle Database 10g New Features:

NID utility has been introduced to change the database name and id.

Automated Storage Management (ASM). ASMB, RBAL, ARBx are the new background processes related to ASM.

New memory structure in SGA i.e. Streams pool (streams_pool_size parameter), useful for datapump activities & streams replication.

From Oracle 10g, the spool command can append to an existing one.
SQL> spool result.log append

Ability to rename tablespaces (except SYSTEM and SYSAUX), whether permanent or temporary, using the following command:

SQL> ALTER TABLESPACE oldname RENAME TO newname;

Oracle Database 11g New Features: 
Ability to mark a table as read only.
SQL> alter table table-name read only;

Temporary tablespace or it's tempfile can be shrinked, up to specified size.
SQL> alter tablespace temp-tbs shrink space;
SQL> alter tablespace temp-tbs shrink space keep n{K|M|G|T|P|E};

Introduction of ADR, single location of all error and trace data in the database, diagnostic_dump parameter

A new parameter is added in 11g, called MEMORY_TARGET, automatic memory management for both the SGA and PGA.

A system privelege is introduced in 11g called SYSASM, and this is granted to users who need to perform ASM related tasks.








Oracle Database 12c New Features: 
Moving and Renaming datafile is now ONLINE, no need to put datafile in offline.
SQL> alter database move datafile 'path' to 'new_path';

No need to shutdown database for changing archive log mode.

Like sysdba, sysoper & sysasm, we have new privileges, in Oracle 12.1.0.
sysbackup for backup operations
sysdg for Data Guard operations
syskm for key management

Patching:
Centralised patching.
We can retrieve OPatch information using sqlplus query, using DBMS_QOPATCH package

SQL> select dbms_qopatch.get_opatch_lsinventory() from dual;

We can test patches on database copies, rolling patches out centrally once testing is complete.

New Commands
create pluggable database ...
alter pluggable database ...
drop pluggable database ...


New background processes - LREG (Listener Registration), SA (SGA Allocator), RM.

Oracle Database 12c Data Pump will allow turning off redo for the import operation (only).
$ impdp ... transform=disable_archive_logging:y

There are lots of differences! 

Some of the big ones are: 

- Multitenant/pluggable databases 
- In Memory (12.1.0.2 
- JSON support (12.1.0.2) 
- Adaptive queries 
- New histogram types 
- SQL enhancements (match_recognize, PL/SQL in the with clause, ...) 

Tuesday, 12 June 2018

Pl/sql Interview Questions

----<<Difference between Bulk Collect and Culk Bind >>

Difference between Bulk collect and Forall. Bulk collect: is a CLAUSE. 
is used to fetch the records from the cursor. Forall: is a STATEMENT. ... 
The body of the FORALL statement is a single DML statement -- an INSERT, UPDATE, or DELETE

---What is the difference between normal sl and dynamic sql


Static or Embedded SQL are SQL statements in an application that do not change at runtime and, 
therefore, can be hard-coded into the application. Dynamic SQL is SQL statements that are constructed 
at runtime; for example, the application may allow users to enter their own queries.

Dynamic SQL is a programming technique that enables you to build SQL statements dynamically at runtime. You can create more general purpose, flexible applications by using dynamic SQL because the full text of a SQL statement may be unknown at compilation.

Below mentioned are the basic differences between Static or Embedded and Dynamic or Interactive SQL:

STATIC (EMBEDDED) SQL   DYNAMIC (INTERACTIVE) SQL
In Static SQL, how database will be accessed is predetermined in the embedded SQL statement. 
   In Dynamic SQL, how database will be accessed is determined at run time.
It is more swift and efficient. It is less swift and efficient.
SQL statements are compiled at compile time.    SQL statements are compiled at run time.
Parsing, Validation, Optimization and Generation of application plan are done at compile time. 
 Parsing, Validation, Optimization and Generation of application plan are done at run time.
It is generally used for situations where data is distributed uniformly.  
  It is generally used for situations where data is distributed non uniformly.
EXECUTE IMMEDIATE, EXECUTE and PREPARE statements are not used. EXECUTE IMMEDIATE, 
EXECUTE and PREPARE statements are used.
It is less flexible.    It is more flexible.
Limitation of Dynamic SQL:
We cannot use some of the SQL statements Dynamically.
Performance of these statements is poor as compared to Static SQL.

Limitations of Static SQL:
They do not change at runtime thus are hard-coded into applications

--Difference betwen view and mv
View    Materialized View
View is nothing but a set a sql statements together which join single or multiple tables and  shows the data  
Materialized view is a concept mainly used in Datawarehousing,
views does not store the data themselves but point to the data.
Materialized view store the data. Reason being it is easier/faster to access the data
View is a logical or virtual memory which is based on select query 
materialized view is physical duplicate data in a table,
it works faster than simple, Its works as snap shot and used for security purposes
simple view is the view in which we can not make DML command if the view is created by multiple tables
we can make DML command in materialize view
A view takes the output of a query and makes it appear like 
a virtual table Materialized views are schema objects that can be used to summarize, precompute, replicate, 
and distribute data. E.g. to construct a data warehouse.
You can use a view in most places where a table can be used 
A materialized view can be stored in the same database as its base table(s) or in a different database.
All operations performed on a view will affect data in the base table 
and so are subject to the integrity constraints and triggers of the base table.   
A materialized view provides indirect access to table data by storing the results of a query in a separate schema
object. Unlike an ordinary view, which does not take up any storage space or contain any data
/
/*Difference among Index by table, Nested table and Varray

Index by table
Nested table
Varray*/


1) What is GTT  ?

a) The statement to create a global temporary table (GTT) is similar to the definition 
of an ordinary table with the addition of the keywords GLOBAL TEMPORARY. In the clause
ON COMMIT, you specify if a table is bound to a transaction (DELETE ROWS) or 
to a session (PRESERVE ROWS).
When using a global temporary table you need only define the table once 

for the entire schema and then any user can insert directly into the table without the need to re-create 
the global temporary table.


ex :--create global temporary table
sum_quantity
(sum_qty number) 
---a) ON COMMIT    :-
---b) DELETE ROWS  :-
---c) PRESERVE ROWS:- The rows of the table will be preserved.
/
---What is dynamic sql 
ans)  Compilation and execution will happend at run time.Its useful forwhen we dont know column names,table names
at run time,oracle olacle uses "late binding " for dynamic sql and "early binding" for statc sql.
Fake compilation will happen at compilation stage but actuval compilation will happend at run time.

Methods of implementing is
1)execute immediate
2)  using a package called DBMS_SQL package
we cane use trucate or drop command directly in plsql .So we are using execute immediate
we can pass table name and column name to drop table at run time .

/
--wt is the difference between cursor and ref cursor

nornal cursor :- create one varible and that each variable can hold one particular set of result.
refcursor is reference curosr the most useful for dynamic sql concepts.
ref cursor :it can store different result set at different points of time.
ref cursor is user defined datatype which are very much helpful to return multiple records 
from procedure or functions
ex:refcur

Declare
type test is ref cursor;
var test;
vrev emp%rowtype;
vrec2 dept%rowtype;
Begin
open var for 'select * from emp';
Loop
fetch var into vrec;
exit when var%notfound;
dbms_output.put_line(vrec.ename);
End ;
open var for 'select * from dept';
Loop
fetch var into vrec2;
exit when var%notfound;
dbms_output.put_line(vrec2.dname);
End loop;;
close var;
end;
refcursor are 2 types :strong and week 
/
--1) wt is the difference between cusroe and ref cusrsor?

A) ref cursor is a pointer to a result set. This is normally used to open a query on the database server,
then leave it up to the client to fetch the result it needs. A ref cursor is also a cursor, 
though normally ther term cursor is used when discussing static SQL.
2)In case of a normal explict cursor, the SQL query has to be defined at the time of declaring the cursor itself.
For example :
DECLARE
CURSOR cr is SELECT * FROM TAB;
3)In case of REF Cursor, the cursor declartion is not associated with any SQL query,
 it is associated with a query at a later stage which brings in a lot of flexibility as different SQL
  queries can be associated with the cursor (one at a time, offcourse) programatically.

For example :
DECLARE
TYPE rc is ref cursor;
cur1 rc;
BEGIN
open cur1 for 'select * from tab';
#some code
End;

1) A ref cursor can not be used in CURSOR FOR LOOP, it must be used in simple CURSOR LOOP statement as in example.

2) A ref cursor is defined at runtime and can be opened dynamically but 
a regular cursor is static and defined at compile time.

3) A ref cursor can be passed to another PL/SQL routine (function or procedure)
or returned to a client. A regular cursor cannot be returned to a client application 
and must be consumed within same routine.

4) A ref cursor incurs a parsing penalty because it cannot cached but regular 
cursor will be cached by PL/SQL which can lead to a significant reduction in CPU utilization.

5) A regular cursor can be defined outside of a procedure or a function as a global package variable. 
A ref cursor cannot be; it must be local in scope to a block of PL/SQL code.

6) A regular cursor can more efficiently retrieve data than ref cursor.
A regular cursor can implicitly fetch 100 rows at a time if used with CURSOR FOR LOOP. 
A ref cursor must use explicit array fetching.

Use of ref cursors should be limited to only when you have a requirement of returning result sets to clients 
and when there is NO other efficient/effective means of achieving the goal.
/
----+ve and -ne value query with case
select sum(case when sal<0 Then sal end) nval,
sum(case when sal>0 Then sal end) pval  from emp
/
-----+ve and -ne value query with sign
select sum(decode(sign(sal),1,sal)),sum(decode(sign(sal),-1,sal)) from emp

/

---q) what is collection and examples with types

And) A Collection is an ordered group of elements of particular data types. It can be a collection 
of simple data type or
complex data type (like user-defined or record types).

Collections are most useful things when a large data of the same type need to be processed or manipulated. 
Collections can be populated
and manipulated as whole using 'BULK' option in Oracle.

Collections are classified based on the structure, subscript, and storage as shown below.

Index-by-tables (also known as Associative Array)
Nested tables
Varrays

At any point, data in the collection can be referred by three terms Collection name, 
Subscript, Field/Column name as "<collection_name>(<subscript>).<column_name>". You are going 
to learn about these above-mentioned collection categories further in the below section.
Varrays

Varray is a collection method in which the size of the array is fixed.
The array size cannot be exceeded than its fixed value. The subscript of the Varray is of a numeric value. 
Following are the attributes of Varrays.

Upper limit size is fixed
Populated sequentially starting with the subscript '1'
This collection type is always dense, i.e. we cannot delete any array elements. 
Varray can be deleted as a whole, or it can be trimmed from the end.
Since it always is dense in nature, it has very less flexibility.
It is more appropriate to use when the array size is known and to perform similar activities 
on all the array elements.
The subscript and sequence always remain stable, i.e. the subscript and count of the collection is always same.
They need to be initialized before using them in programs. Any operation (except EXISTS operation) 
on an uninitialized collection will throw an error.
It can be created as a database object, which is visible throughout the database or inside the subprogram, 
which can be used only in that subprogram.
The below figure will explain the memory allocation of Varray (dense) diagrammatically.

Subscript   1   2   3   4   5   6   7
Value   Xyz Dfv Sde Cxs Vbc Nhu Qwe
Syntax for VARRAY:

TYPE <type_name> IS VARRAY (<SIZE>) OF <DATA_TYPE>;

In the above syntax, type_name is declared as VARRAY of the type 'DATA_TYPE' for the given size limit. 
The data type can be either simple or complex type.
Nested Tables
A Nested table is a collection in which the size of the array is not fixed. It has the numeric subscript type. 
Below are more descriptions about nested table type.
The Nested table has no upper size limit.
Since the upper size limit is not fixed, the collection, memory needs to be extended each time before we use it.
We can extend the collection using 'EXTEND' keyword.
Populated sequentially starting with the subscript '1'.
This collection type can be of both dense and sparse, i.e. we can create the collection as a dense, and we can also 
delete the individual array element randomly, which make it as sparse.
It gives more flexibility regarding deleting the array element.
It is stored in the system generated database table and can be used in the select query to fetch the values.
The subscript and sequence are not stable, i.e. the subscript and the count of the array element can vary.
They need to be initialized before using them in programs. Any operation (except EXISTS operation)
on the uninitialized collection will throw an error.
It can be created as a database object, which is visible throughout the database or inside the subprogram,
which can be used only in that subprogram.
The below figure will explain the memory allocation of Nested Table (dense and sparse) diagrammatically. 
The black colored element space denotes the empty element in a collection i.e. sparse.

Subscript   1   2   3   4   5   6   7
Value (dense)   Xyz Dfv Sde Cxs Vbc Nhu Qwe
Value(sparse)   Qwe     Asd Afg     Asd Wer
Syntax for Nested Table:

TYPE <tvpe name> IS TABLE OF <DATA TYPE>;
In the above syntax, type_name is declared as Nested table collection of the type 'DATA_TYPE'.
The data type can be either simple or complex type.
Index-by-table
Index-by-table is a collection in which the array size is not fixed. Unlike the other collection types, in the index-by-table collection the subscript can consist be defined by the user. Following are the attributes of index-by-table.

The subscript can of integer or strings. At the time of creating the collection, the subscript
type should be mentioned.
These collections are not stored sequentially.
They are always sparse in nature.
The array size is not fixed.
They cannot be stored in the database column. They shall be created and used in any program in that particular
session.
They give more flexibility in terms of maintaining subscript.
The subscripts can be of negative subscript sequence also.
They are more appropriate to use for relatively smaller collective values in which the 
collection can be initialized and used within the same subprograms.
They need not be initialized before start using them.
It cannot be created as a database object. It can only be created inside the subprogram, 
which can be used only in that subprogram.
BULK COLLECT cannot be used in this collection type as the subscript should be given explicitly 
for each record in the collection.
The below figure will explain the memory allocation of Nested Table (sparse) diagrammatically. 
The black colored element space denotes the empty element in a collection i.e. sparse.

Subscript (varchar) FIRST   SECOND  THIRD   FOURTH  FIFTH   SIXTH   SEVENTH
Value(sparse)   Qwe     Asd Afg     Asd Wer
Syntax for Index-by-Table

TYPE <type_name> IS TABLE OF <DATA_TYPE> INDEX BY YARCHAR2 (10);

In the above syntax, type_name is declared as an index-by-table collection of the type 'DATA_TYPE'. 
The data type can be either simple or complex type. The subsciprt/index variable is given as VARCHAR2 
type with maximum size as 10.
<<Methods of clooetion>>
1) EXISTS ,count,limit,first,last,prior,next,delete,delete(n)..
/
--<<Difference between Bulk Collect and Culk Bind >>

Difference between Bulk collect and Forall. Bulk collect: is a CLAUSE. 
is used to fetch the records from the cursor. Forall: is a STATEMENT. ... 
The body of the FORALL statement is a single DML statement -- an INSERT, UPDATE, or DELETE

Tuesday, 15 May 2018

PL/SQL - Exceptions

In this chapter, we will discuss Exceptions in PL/SQL. An exception is an error condition during a program execution. PL/SQL supports programmers to catch such conditions using EXCEPTION block in the program and an appropriate action is taken against the error condition. There are two types of exceptions −
  • System-defined exceptions
  • User-defined exceptions

Syntax for Exception Handling

The general syntax for exception handling is as follows. Here you can list down as many exceptions as you can handle. The default exception will be handled using WHEN others THEN −
DECLARE 
   <declarations section> 
BEGIN 
   <executable command(s)> 
EXCEPTION 
   <exception handling goes here > 
   WHEN exception1 THEN  
      exception1-handling-statements  
   WHEN exception2  THEN  
      exception2-handling-statements  
   WHEN exception3 THEN  
      exception3-handling-statements 
   ........ 
   WHEN others THEN 
      exception3-handling-statements 
END;

Example

Let us write a code to illustrate the concept. We will be using the CUSTOMERS table we had created and used in the previous chapters −
DECLARE 
   c_id customers.id%type := 8; 
   c_name customerS.Name%type; 
   c_addr customers.address%type; 
BEGIN 
   SELECT  name, address INTO  c_name, c_addr 
   FROM customers 
   WHERE id = c_id;  
   DBMS_OUTPUT.PUT_LINE ('Name: '||  c_name); 
   DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr); 

EXCEPTION 
   WHEN no_data_found THEN 
      dbms_output.put_line('No such customer!'); 
   WHEN others THEN 
      dbms_output.put_line('Error!'); 
END; 
/
When the above code is executed at the SQL prompt, it produces the following result −
No such customer!  

PL/SQL procedure successfully completed. 
The above program displays the name and address of a customer whose ID is given. Since there is no customer with ID value 8 in our database, the program raises the run-time exception NO_DATA_FOUND, which is captured in the EXCEPTION block.

Raising Exceptions

Exceptions are raised by the database server automatically whenever there is any internal database error, but exceptions can be raised explicitly by the programmer by using the command RAISE. Following is the simple syntax for raising an exception −
DECLARE 
   exception_name EXCEPTION; 
BEGIN 
   IF condition THEN 
      RAISE exception_name; 
   END IF; 
EXCEPTION 
   WHEN exception_name THEN 
   statement; 
END; 
You can use the above syntax in raising the Oracle standard exception or any user-defined exception. In the next section, we will give you an example on raising a user-defined exception. You can raise the Oracle standard exceptions in a similar way.

User-defined Exceptions

PL/SQL allows you to define your own exceptions according to the need of your program. A user-defined exception must be declared and then raised explicitly, using either a RAISE statement or the procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR.
The syntax for declaring an exception is −
DECLARE 
   my-exception EXCEPTION; 

Example

The following example illustrates the concept. This program asks for a customer ID, when the user enters an invalid ID, the exception invalid_id is raised.
DECLARE 
   c_id customers.id%type := &cc_id; 
   c_name customerS.Name%type; 
   c_addr customers.address%type;  
   -- user defined exception 
   ex_invalid_id  EXCEPTION; 
BEGIN 
   IF c_id <= 0 THEN 
      RAISE ex_invalid_id; 
   ELSE 
      SELECT  name, address INTO  c_name, c_addr 
      FROM customers 
      WHERE id = c_id;
      DBMS_OUTPUT.PUT_LINE ('Name: '||  c_name);  
      DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr); 
   END IF; 

EXCEPTION 
   WHEN ex_invalid_id THEN 
      dbms_output.put_line('ID must be greater than zero!'); 
   WHEN no_data_found THEN 
      dbms_output.put_line('No such customer!'); 
   WHEN others THEN 
      dbms_output.put_line('Error!');  
END; 
/
When the above code is executed at the SQL prompt, it produces the following result −
Enter value for cc_id: -6 (let's enter a value -6) 
old  2: c_id customers.id%type := &cc_id; 
new  2: c_id customers.id%type := -6; 
ID must be greater than zero! 
 
PL/SQL procedure successfully completed. 

Pre-defined Exceptions

PL/SQL provides many pre-defined exceptions, which are executed when any database rule is violated by a program. For example, the predefined exception NO_DATA_FOUND is raised when a SELECT INTO statement returns no rows. The following table lists few of the important pre-defined exceptions −
ExceptionOracle ErrorSQLCODEDescription
ACCESS_INTO_NULL06530-6530It is raised when a null object is automatically assigned a value.
CASE_NOT_FOUND06592-6592It is raised when none of the choices in the WHEN clause of a CASE statement is selected, and there is no ELSE clause.
COLLECTION_IS_NULL06531-6531It is raised when a program attempts to apply collection methods other than EXISTS to an uninitialized nested table or varray, or the program attempts to assign values to the elements of an uninitialized nested table or varray.
DUP_VAL_ON_INDEX00001-1It is raised when duplicate values are attempted to be stored in a column with unique index.
INVALID_CURSOR01001-1001It is raised when attempts are made to make a cursor operation that is not allowed, such as closing an unopened cursor.
INVALID_NUMBER01722-1722It is raised when the conversion of a character string into a number fails because the string does not represent a valid number.
LOGIN_DENIED01017-1017It is raised when a program attempts to log on to the database with an invalid username or password.
NO_DATA_FOUND01403+100It is raised when a SELECT INTO statement returns no rows.
NOT_LOGGED_ON01012-1012It is raised when a database call is issued without being connected to the database.
PROGRAM_ERROR06501-6501It is raised when PL/SQL has an internal problem.
ROWTYPE_MISMATCH06504-6504It is raised when a cursor fetches value in a variable having incompatible data type.
SELF_IS_NULL30625-30625It is raised when a member method is invoked, but the instance of the object type was not initialized.
STORAGE_ERROR06500-6500It is raised when PL/SQL ran out of memory or memory was corrupted.
TOO_MANY_ROWS01422-1422It is raised when a SELECT INTO statement returns more than one row.
VALUE_ERROR06502-6502It is raised when an arithmetic, conversion, truncation, or sizeconstraint error occurs.
ZERO_DIVIDE014761476It is raised when an attempt is made to divide a number by zero.

Monday, 14 May 2018

Cursors And Bulk Collect

Cursors And Bulk Collect

CURSORS

Cursor is a pointer to memory location which is called as context area which contains the information necessary for processing, including the number of rows processed by the statement, a pointer to the parsed representation of the statement, and the active set which is the set of rows returned by the query.
Cursor contains two parts
  • Header
  • Body
Header includes cursor name, any parameters and the type of data being loaded.
Body includes the select statement.
Ex:
Cursor c(dno in number) return dept%rowtype is select *from dept;
In the above
Header – cursor c(dno in number) return dept%rowtype
Body – select *from dept
CURSOR TYPES
  • Implicit (SQL)
  • Explicit
  1. Parameterized cursors
  2. REF cursors
Explicit Cursor: The set of rows returned by a query can consist of zero, one, or multiple rows, depending on how many rows meet your search criteria. When a query returns multiple rows, you can explicitly define a cursor to process the rows. You use three commands to control the cursor:
CURSOR STAGES
  1. Open
  2. Fetch
  3. Close
Implicit Cursors: ORACLE implicitly opens a cursor to process each SQL statement not associated with an explicitly declared cursor.PL/SQL lets you refer to the most recent implicit cursor as the SQL” cursor. So, although you cannot use the OPEN,
FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to access information about the most recently executed SQL statement.
CURSOR ATTRIBUTES
  1. %found
  2. %notfound
  3. %rowcount
  4. %isopen
  5. %bulk_rowcount
  6. %bulk_exceptions
CURSOR DECLERATION
Syntax:
Cursor <cursor_name> is select statement;
Ex:
Cursor c is select *from dept;
CURSOR LOOPS
  1. Simple loop
  2. While loop
  3. For loop
SIMPLE LOOP
Syntax:
Loop
Fetch <cursor_name> into <record_variable>;
Exit when <cursor_name> % notfound;
<statements>;
End loop;
Ex:
Output:
Name = saketh
Name = srinu
Name = satish
Name = sudha
WHILE LOOP
Syntax:
While <cursor_name> % found loop
Fetch <cursor_name> nto <record_variable>;
<statements>;
End loop;
Ex:
Output:
Name = saketh
Name = srinu
Name = satish
Name = sudha
FOR LOOP
Syntax:
for <record_variable> in <cursor_name> loop
<statements>;
End loop;
Ex:
Output:
Name = saketh
Name = srinu
Name = satish
Name = sudha
PARAMETARIZED CURSORS
  1. This was used when you are going to use the cursor in more than one place with different values for the same where clause.
  2. Cursor parameters must be in mode.
  3. Cursor parameters may have default values.
  4. The scope of cursor parameter is within the select statement.
Ex:

PACKAGED CURSORS WITH HEADER IN SPEC AND BODY IN PACKAGE BODY
  1. Cursors declared in packages will not close automatically.
  2. In packaged cursors you can modify the select statement without making any changes to the cursor header in the package specification.
  3. Packaged cursors with must be defined in the package body itself, and then use it as global for the package.
  4. You can not define the packaged cursor in any subprograms.
  5. Cursor declaration in package with out body needs the return clause.

REF CURSORS AND CURSOR VARIABLES
  1. This is unconstrained cursor which will return different types depends upon the user input.
  2. Ref cursors cannot be closed implicitly.
  3. Ref cursor with return type is called strong cursor.
  4. Ref cursor without return type is called weak cursor.
  5. You can declare ref cursor type in package spec as well as body.
  6. You can declare ref cursor types in local subprograms or anonymous blocks.
  7. Cursor variables can be assigned from one to another.
  8. You can declare a cursor variable in one scope and assign another cursor variable with different scope, then you can use the cursor variable even though the assigned cursor variable goes out of scope.
  9. Cursor variables can be passed as parameters to the subprograms.
  10. Cursor variables modes are in or out or in out.
  11. Cursor variables cannot be declared in package spec and package body (excluding subprograms).
  12. You cannot user remote procedure calls to pass cursor variables from one server to another.
  13. Cursor variables cannot use for update clause.
  14. You can not assign nulls to cursor variables.
  15. You cannot compare cursor variables for equality, inequality and nullity.

CURSOR EXPRESSIONS
  1. You can use cursor expressions in explicit cursors.
  2. You can use cursor expressions in dynamic SQL.
  3. You can use cursor expressions in REF cursor declarations and variables.
  4. You cannot use cursor expressions in implicit cursors.
  5. Oracle opens the nested cursor defined by a cursor expression implicitly as soon as it fetches the data containing the cursor expression from the parent or outer cursor.
  6. Nested cursor closes if you close explicitly.
  7. Nested cursor closes whenever the outer or parent cursor is executed again or closed or canceled.
  8. Nested cursor closes whenever an exception is raised while fetching data from a parent cursor.
  9. Cursor expressions cannot be used when declaring a view.
  10. Cursor expressions can be used as an argument to table function.
  11. You cannot perform bind and execute operations on cursor expressions when using the cursor expressions in dynamic SQL.
USING NESTED CURSORS OR CURSOR EXPRESSIONS
 CURSOR CLAUSES
  1. Return
  2. For update
  3. Where current of
  4. Bulk collect
RETURN
Cursor c return dept%rowtype is select *from dept;
Or
Cursor c1 is select *from dept;
Cursor c return c1%rowtype is select *from dept;
Or
Type t is record(deptno dept.deptno%type, dname dept.dname%type);
Cursor c return t is select deptno, dname from dept;
FOR UPDATE AND WHERE CURRENT OF
Normally, a select operation will not take any locks on the rows being accessed. This will allow other sessions connected to the database to change the data being selected. The result set is still consistent. At open time, when the active set is determined, oracle takes a snapshot of the table. Any changes that have been committed prior to this point are reflected in the active set. Any changes made after this point, even if they are committed, are not reflected unless the cursor is reopened, which will evaluate the active set again.
However, if the FOR UPDATE caluse is pesent, exclusive row locks are taken on the rows in the active set before the open returns. These locks prevent other sessions from changing the rows in the active set until the transaction is committed or rolled back. If another session already has locks on the rows in the active set, then SELECT … FOR UPDATE operation will wait for these locks to be released by the other session. There is no time-out for this waiting period. The SELECT…FOR UPDATE will hang until the other session releases the lock. To handle this situation, the NOWAIT clause is available.
Syntax:
Select …from … for update of column_name [wait n];
If the cursor is declared with the FOR UPDATE clause, the WHERE CURRENT OF clause can be used in an update or delete statement.
Syntax:
Where current of cursor;

BULK COLLECT
  1. This is used for array fetches
  2. With this you can retrieve multiple rows of data with a single roundtrip.
  3. This reduces the number of context switches between the pl/sql and sql engines.
  4. Reduces the overhead of retrieving data.
  5. You can use bulk collect in both dynamic and static sql.
  6. You can use bulk collect in select, fetch into and returning into clauses.
  7. SQL engine automatically initializes and extends the collections you reference in the bulk collect clause.
  8. Bulk collect operation empties the collection referenced in the into clause before executing the query.
  9. You can use the limit clause of bulk collect to restrict the no of rows retrieved.
  10. You can fetch into multible collections with one column each.
  11. Using the returning clause we can return data to the another collection.
BULK COLLECT IN FETCH

BULK COLLECT IN SELECT

LIMIT IN BULK COLLECT
You can use this to limit the number of rows to be fetched.
 MULTIPLE FETCHES IN INTO CLAUSE
 RETURNING CLAUSE IN BULK COLLECT
You can use this to return the processed data to the ouput variables or typed variables.
POINTS TO REMEMBER
  1. Cursor name can be up to 30 characters in length.
  2. Cursors declared in anonymous blocks or subprograms closes automatically when that block terminates execution.
  3. %bulk_rowcount and %bulk_exceptions can be used only with forall construct.
  4. Cursor declarations may have expressions with column aliases.
  5. These expressions are called virtual columns or calculated columns.

hr schema

 CREATE TABLE regions     ( region_id      NUMBER         CONSTRAINT  region_id_nn NOT NULL      , region_name    VARCHAR2(25)      );      ...