Monday, November 21, 2011

Type of Cursors

Two types:

1. Implicit cursor
2. Explicit cursor

Implicit cursor: Are used by oracle.
eg1:
select name into var_name from emp;
eg2:
FOR r IN ( SELECT * FROM source_table )
LOOP

UPDATE target_table tgt
SET tgt.object_name = r.object_name
, tgt.object_type = r.object_type
WHERE tgt.object_id = r.object_id;

u := u + SQL%ROWCOUNT;

IF SQL%ROWCOUNT = 0 THEN
INSERT INTO target_table
( object_id, object_name, object_type )
VALUES
( r.object_id, r.object_name, r.object_type );
i := i + 1;
END IF;

END LOOP;

Explicit Cursors :For explicit cursors developer should do the following things

1. Declare the cursor
CURSOR company_cur IS
SELECT company_id FROM company;

2. Open the cursor (if not already open)
OPEN company_cur ;
3. Fetch one or more rows from the cursor
LOOP
FETCH company_cur INTO var_emplid;

EXIT WHEN company_cur %NOTFOUND;
-- do some data process here

END LOOP;

4. Close the cursor
CLOSE company_cur;

No comments: