Connecting Tech Pros Worldwide Forums | Help | Site Map

PL/SQL-CURSOR - 4

debasisdas's Avatar
Moderator
 
Join Date: Dec 2006
Location: Bangalore ,India
Posts: 7,569
#1   Sep 17 '07
This thread contains some useful tips/samples regarding some advance concepts in cursors.

FEW MORE EXAMPLES
===================
Expand|Select|Wrap|Line Numbers
  1. declare
  2. er emp%rowtype;
  3. cursor c1 is select * from emp;
  4. begin
  5. open c1;
  6. loop
  7. fetch c1 into er;
  8. exit when c1%notfound;
  9. if er.job='SALESMAN' then
  10. dbms_output.put_line(er.empno||' '||er.ename||'  '||er.sal||'  '||er.sal*1.10);
  11.  
  12. elsif er.job='CLERK' then
  13. dbms_output.put_line(er.empno||' '||er.ename||'  '||er.sal||'  '||er.sal*1.08);
  14.  
  15. else
  16. dbms_output.put_line(er.empno||' '||er.ename||'  '||er.sal||'  '||'No ince req.');
  17. end if;
  18.  
  19. end loop;
  20. close c1;
  21. end;
  22.  
NOTE:--PLEASE TRY THE ABOVE CODE IN SCOTT SCHEMA

EXAMPLE #1
--------------------
Expand|Select|Wrap|Line Numbers
  1. begin
  2. --no need to open and close.
  3. for dr in (select * from dept) loop
  4. dbms_output.put_line(dr.deptno||'  '||dr.dname||'  '||dr.loc);
  5. end loop;
  6. end;
  7.  
EXAMPLE #2
----------------------
Expand|Select|Wrap|Line Numbers
  1. declare
  2. --cursor is declared
  3. cursor c1 is select * from dept;
  4. -- a cur type variable is declared
  5. dr c1%rowtype;
  6. begin
  7. -- open the cursor
  8. open c1;
  9. --fetch into the target variable
  10. fetch c1 into dr;
  11. -- check for existance of more dat in the cursor
  12. while (c1%found=TRUE) loop
  13. fetch c1 into dr;
  14. dbms_output.put_line(dr.deptno||' '||dr.dname||'   '||dr.loc);
  15. --end the loop
  16. end loop;
  17. --close the cursor.
  18. close c1;
  19. end;
  20.  

SAMPLE PROGRAM TO SHOW USE OF RECORD TYPE IN CURSOR
-----------------------------------------------------------------------------------------------------------
Expand|Select|Wrap|Line Numbers
  1. declare
  2. TYPE MYTYPE IS RECORD
  3. (
  4. MENAME VARCHAR2(10),
  5. MMGR NUMBER(4)
  6. );
  7. mm mytype;
  8. CURSOR C1 IS
  9. select ename,mgr from emp where deptno=20 and job='CLERK';
  10. begin
  11. open C1;
  12. LOOP
  13. FETCH C1 INTO mm.mename,mm.mmgr;
  14. EXIT WHEN C1%NOTFOUND;
  15. DBMS_OUTPUT.PUT_LINE(mm.mename || ' '|| mm.mmgr);
  16. END LOOP;
  17. CLOSE C1;
  18. END;
  19.  

Also Check PL/SQL-CURSOR - 5



Reply