Analytics

Sunday, March 24, 2013

Oracle Cursor

For every SQL statement execution certain area in memory is allocated. PL/SQL allow you to name this area. This private SQL area is called context area or cursor. A cursor acts as a handle or pointer into the context area. A PL/SQL program controls the context area using the cursor. Cursor represents a structure in memory and is different from cursor variable.

When you declare a cursor, you get a pointer variable, which does not point any thing. When the cursor is opened, memory is allocated and the cursor structure is created. The cursor variable now points the cursor. When the cursor is closed the memory allocated for the cursor is released.

Cursors allow the programmer to retrieve data from a table and perform actions on that data one row at a time.

There are two types of cursors implicit cursors and explicit cursors.

Implicit cursors:

For SQL queries returning single row PL/SQL declares implicit cursors. Implicit cursors are simple SELECT statements and are written in the BEGIN block (executable section) of the PL/SQL. Implicit cursors are easy to code, and they retrieve exactly one row. PL/SQL implicitly declares cursors for all DML statements. The most commonly raised exceptions here are NO_DATA_FOUND or TOO_MANY_ROWS.

Syntax:

SELECT ename, sal INTO ena, esa FROM EMP WHERE EMPNO = 7844;

Note: Ename and sal are columns of the table EMP and ena and esa are the variables used to store ename and sal fetched by the query.

Explicit Cursors:

Explicit cursors are used in queries that return multiple rows. The set of rows fetched by a query is called active set. The size of the active set meets the search criteria in the select statement. Explicit cursor is declared in the DECLARE section of PL/SQL program.

Syntax:

CURSOR cursor_name IS select statement

Sample Code:

DECLARE 
CURSOR emp_cur IS SELECT ename FROM EMP;
BEGIN
     ------- 
     -------
END;

A cursor is a mechanism by which you can assign a name to a "select statement" and manipulate the information within that SQL statement.

You can manipulate cursors using the OPEN, FETCH, and CLOSE statements.

When you need to get information about the current status of your cursor, or the result of the last fetch from a cursor, you will access cursor attributes.

PL/SQL offers a total of six attributes:

  1. %FOUND- Returns TRUE if record was fetched successfully; FALSE otherwise.
  2. %NOTFOUND- Returns TRUE is record was not fetched successfully; FALSE otherwise.
  3. %ROWCOUNT - Returns number of records fetched from cursor at that point in time.
  4. %ISOPEN- Returns TRUE is cursor is open; FALSE otherwise.
  5. %BULK_ROWCOUNT - Returns the number of records modified by the FORALL statement for each collection element.
  6. %BULK_EXCEPTIONS- Returns exception information for rows modified by the FORALL statement for each collection element.

Examples

1. An explicit cursor that selects data.

SQL> declare
  2    cursor emps
  3    is select *
  4         from employees
  5        where rownum < 6
  6        order by 1;
  7
  8    emp employees%rowtype;
  9    row number := 1;
 10  begin
 11    open emps;
 12    fetch emps into emp;
 13
 14    loop
 15      if emps%FOUND then
 16        dbms_output.put_line('Looping over record '
 17                   ||row|| ' of ' || emps%ROWCOUNT);
 18        fetch emps into emp;
 19        row := row + 1;
 20      elsif emps%NOTFOUND then
 21        exit; -- EXIT statement exits the LOOP
 22      end if;
 23    end loop;
 24
 25    if emps%ISOPEN then
 26      close emps;
 27    end if;
 28  end;
 29  /
Looping over record 1 of 1
Looping over record 2 of 2
Looping over record 3 of 3
Looping over record 4 of 4
Looping over record 5 of 5

PL/SQL procedure successfully completed.

2. An explicit cursor fetch loop.

SQL> DECLARE
  2    myLecturerID    lecturer.id%TYPE;
  3    firstName    lecturer.first_name%TYPE;
  4    v_LastName     lecturer.last_name%TYPE;
  5
  6    v_Major lecturer.major%TYPE := 'Computer Science';
  7
  8    CURSOR cursorValue IS
  9      SELECT id, first_name, last_name
 10        FROM lecturer
 11        WHERE major = v_Major;
 12  BEGIN
 13    OPEN cursorValue;
 14    LOOP
 15      FETCH cursorValue INTO myLecturerID, firstName
 16    , v_LastName;
 17      EXIT WHEN cursorValue%NOTFOUND;
 18    END LOOP;
 19    CLOSE cursorValue;
 20  END;
 21  /

PL/SQL procedure successfully completed.

3. Use cursor to store the row count.

SQL> declare
  2       l_emp_count number;
  3       i number; -- We will use this as our counter
  4
  5       CURSOR cursorValue IS
  6       select count(*)
  7       from lecturer;
  8       begin
  9       OPEN cursorValue;
 10       FETCH cursorValue INTO l_emp_count;
 11
 12       FOR i IN 1 .. l_emp_count LOOP
 13       dbms_output.put_line('Employee ' || i);
 14       END LOOP;
 15
 16       CLOSE cursorValue;
 17  end;
 18  /
Employee 1
Employee 2
Employee 3
Employee 4
Employee 5
Employee 6
Employee 7
Employee 8
Employee 9
Employee 10
Employee 11
Employee 12

PL/SQL procedure successfully completed.

4. Cursor with parameter.

SQL> declare
  2    cursor cursorValue (p_deptid in number)
  3    is select *
  4         from employees
  5        where department_id = p_deptid;
  6
  7    l_emp employees%rowtype;
  8  begin
  9    open cursorValue(30);
 10    loop
 11      fetch cursorValue into l_emp;
 12      exit when cursorValue%notfound;
 13      dbms_output.put('Emp id ' || l_emp.employee_id || ' is ');
 14      dbms_output.put_line(l_emp.last_name);
 15    end loop;
 16    close cursorValue;
 17
 18    dbms_output.put_line('Getting employees for department 90');
 19    open cursorValue(90);
 20    loop
 21      fetch cursorValue into l_emp;
 22      exit when cursorValue%notfound;
 23      dbms_output.put('Emp id ' || l_emp.employee_id || ' is ');
 24      dbms_output.put_line(l_emp.last_name);
 25    end loop;
 26    close cursorValue;
 27  end;
 28  /
Getting employees for department 90

PL/SQL procedure successfully completed.

Oracle Views

A view is simply the representation of a SQL statement that is stored in memory so that it can easily be re-used.

Views are known as logical tables. They represent the data of one or more tables. A view derives its data from the tables on which it is based. These tables are called base tables. Views can be based on actual tables or another view also.

Whatever DML operations you performed on a view they actually affect the base table of the view. You can treat views same as any other table. You can Query, Insert, Update and delete from views, just as any other table.

Views are very powerful and handy since they can be treated just like any other table but do not occupy the space of a table.

The following sections explain how to create, replace, and drop views using SQL commands.

Create View

Use the CREATE VIEW statement to define a view, which is a logical table based on one or more tables or views. A view contains no data itself. The tables upon which a view is based are called base tables.

OR REPLACE

Specify "OR REPLACE" to re-create the view if it already exists. You can use this clause to change the definition of an existing view without dropping, re-creating, and regranting object privileges previously granted on it.

Create or Replace a View

SQL>  create or replace view view_t as
  2      select id view_id, data view_data
  3        from t;

View created.

Create view without indiating the column name

SQL> CREATE VIEW EmployeeView AS
  2   select First_Name, Last_Name from Employee;

View created.

Create OR REPLACE VIEW from selected columns in a table

SQL> CREATE OR REPLACE VIEW myView (First_Name, Last_Name) AS
  2      select First_Name,
  3             Last_Name
  4      from Employee
  5      where Salary > 2000;

View created.

Create Force View

SQL>  create view invalid_view as
  2      select * from table_that_does_not_exist;
    select * from table_that_does_not_exist
                  *
ERROR at line 2:
ORA-00942: table or view does not exist

SQL>  create force view invalid_view as
  2      select * from table_that_does_not_exist;

Warning: View created with compilation errors.

Create Materialized View

SQL>  create materialized view my_orders_mv
  2      build immediate
  3    refresh on commit
  4     enable query rewrite
  5    as
  6      select employee_id,
  7             count(*) total_orders
  8        from employees
  9       group by employee_id
 10    /
      from employees
           *
ERROR at line 8:
ORA-00439: feature not enabled: Materialized view rewrite

SQL>  set timing on
SQL>  select * from my_orders_mv;
 select * from my_orders_mv
               *
ERROR at line 1:
ORA-00942: table or view does not exist

Elapsed: 00:00:00.07
SQL>  set timing off

6. Create a view with check option

SQL>  create or replace view department_10 as
  2      select *
  3        from employees
  4       where department_id = 10
  5        with check option;

View created.

Oracle Alter View

Use the ALTER VIEW statement to explicitly recompile a view that is invalid or to modify view constraints. Explicit recompilation lets you locate recompilation errors before run time. You may want to recompile a view explicitly after altering one of its base tables to ensure that the alteration does not affect the view or other objects that depend on it.

You can also use ALTER VIEW to define, modify, or drop view constraints.

This statement does not change the definition of an existing view. To redefine a view, you must use CREATE VIEW with the OR REPLACE keywords.

When you issue an ALTER VIEW statement, Oracle Database recompiles the view regardless of whether it is valid or invalid. The database also invalidates any local objects that depend on the view.

If you alter a view that is referenced by one or more materialized views, then those materialized views are invalidated. Invalid materialized views cannot be used by query rewrite and cannot be refreshed.

Alter view to recompile


SQL>  alter view view_t compile;

View altered.

The COMPILE keyword directs Oracle Database to recompile the view.

Dropping Views

Use the SQL command DROP VIEW to drop a view. For example:

DROP VIEW View_Name;

Oracle SYNONYM

Synonyms are a very powerful feature of Oracle and other SQL-compliant relational database systems. They are used as a database shorthand. They make it possible to shorten the specification of long or complex object names. This is especially useful for shared tables or views. In addition, the use of DATABASE LINKS in synonyms allows transparent access to other databases on other nodes or even other entire systems halfway around the globe.

A synonym is an alternative name for objects such as tables, views, sequences, stored procedures, and other database objects.

Create and drop SYNONYM

SQL> CREATE SYNONYM ShorterNameForEmployee FOR Employee;

Synonym created.

SQL> select * from ShorterNameForEmployee;

ID   FIRST_NAME LAST_NAME  START_DAT END_DATE      SALARY CITY      
---- ---------- ---------- --------- --------- ---------- ----------
01   Jason      Martin     25-JUL-96 25-JUL-06    1234.56 Toronto   
02   Alison     Mathews    21-MAR-76 21-FEB-86    6661.78 Vancouver 
03   James      Smith      12-DEC-78 15-MAR-90    6544.78 Vancouver 
04   Celia      Rice       24-OCT-82 21-APR-99    2344.78 Vancouver 
05   Robert     Black      15-JAN-84 08-AUG-98    2334.78 Vancouver 
06   Linda      Green      30-JUL-87 04-JAN-96    4322.78 New York  
07   David      Larry      31-DEC-90 12-FEB-98    7897.78 New York  
08   James      Cat        17-SEP-96 15-APR-02    1232.78 Vancouver 

8 rows selected.

SQL> DROP SYNONYM ShorterNameForEmployee;

Synonym dropped.

Transaction Rollback Commit

All changes of data in an Oracle database can only be done within a transaction. A transaction must either be committed or rolled back.

Data changed within a transaction is not visible to another session until it is commited.

COMMIT :Make changes done in transaction permanent.
ROLLBACK :Rollbacks the state of database to the last commit point.

Transaction Rollback and commit

SQL> create table t ( x number(1) );

Table created.

SQL> insert into t values ( 1 );

1 row created.

SQL> insert into t values ( 2 );

1 row created.

SQL>
SQL> rollback;

Rollback complete.

SQL> select * from t;

no rows selected

SQL> insert into t values ( 1 );

1 row created.

SQL> insert into t values ( 2 );

1 row created.

SQL> commit;

Commit complete.

SQL> select * from t;

         X
----------
         1
         2