Wednesday, October 31, 2012

Pl/Sql - Cursor

A cursor is a temporary work area created in the system memory when a SQL statement is executed.A cursor contains information on a select statement and the rows of data accessed by it.  This temporary work area is used to store the data retrieved from the database, and manipulate this data. A cursor can hold more than one row, but can process only one row at a time.

Defining a Cursor

A cursor is defined in the declarative part of the PL/SQL block by naming it and associating it with a query
CURSOR <cursorname> IS
 SELECT statement;

Example


CURSOR emp_cur IS
SELECT empno, ename, job, sal
FROM emp;

A Cursor can be manipulated using
– OPEN
– FETCH
– CLOSE

Cursor must be declared before it can be referenced using the OPEN, CLOSE or FETCH statements

The OPEN Statement
    Initializes or opens a cursor
    Cursor must be opened before any rows are returned by the query
OPEN <cursorname>
Example --
           OPEN emp_cur;

The FETCH Statement
    Can be executed repeatedly until all rows have been retrieved
FETCH <cursorname> INTO var1, …, varN;
OR
FETCH <cursorname> INTO record_variable;
    Example
FETCH emp_cur INTO mrec;

The CLOSE Statement
    Closes the cursor and makes the active set undefined
CLOSE <cursorname>;
    Example
CLOSE emp_cur;

Example -

DECLARE
  2     
  3      v_id emp.empno%TYPE;
  4     
  5      CURSOR v_cursor IS SELECT empno FROM emp ORDER BY empno;
  6  BEGIN
  7     
  8      OPEN v_cursor;
  9      LOOP
 10         
 11          FETCH v_cursor INTO v_id;
 12         
 13          EXIT WHEN v_cursor%NOTFOUND;
 14          DBMS_OUTPUT.PUT_LINE('v_id = ' || v_id );
 15      END LOOP;
 16      CLOSE v_cursor;
 17  END;
 18  /

0 comments:

Post a Comment

SQL BASIC

  • Sql-Overview
  • Sql-Sysntax
  • Sql-Normalization
  • RDBMS Concept
  • Sql-Data Type
  • Sql-Operator
  • Sql-Expression
  • Create database
  • Sql-Delete
  • Sql-Select
  • Sql-Create
  • Sql-Like
  • Sql-Join
  • Sql-Insert
  • Sql-Drop Table
  • Sql-Wild Card
  • Sql-Order By
  • Sql-Group By
  • Sql-Index
  • Not Null Constraints
  • Transaction Control
  • Sql-Transaction
  • Sql-In
  • Sql-Distinct
  • Check Constraint
  • Sql Alias
  • Sql-Primary
  • Sql-Where
  • Sql-Update
  • Sql-Alias
  • Sql-Top-Rownum
  • Primary key vs Unique key
  • SQL Interview Question
  • PL/SQL BASIC

  • Variable
  • Block Structure
  • Function
  • Procedure
  • Nested Blog
  • If Statement
  • While Loop
  • For Loop
  • SEO

  • Introduction Seo
  • Top Social Bookmarking List
  • Directory Submission List
  • Classified Ads
  • Key Word Research
  • Html

  • Introduction Html
  • Introduction Css
  • Introduction Java Script
  • Unix

  • Unix
  • Software Testing

  • Software Testing
  • Computer Network

  • Computer Network
  •