Oracle游标存储过程语句


可以用Oracle已经存在的账号scott密码triger登陆进去用里面已存在的表来做试验。 

  1. create or replace procedure lpmtest2   
  2. as    
  3.   para1 varchar2(10);   
  4.   cursor  youbiao is  select ename from test where sal>1300;   
  5. begin   
  6.   open youbiao;   
  7.   loop   
  8.     fetch youbiao into para1;   
  9.     exit when youbiao%notfound;   
  10.     dbms_output.put_line('++:'||para1);   
  11.   end loop;   
  12.   close youbiao;   
  13. end;  

代码

  1. create or replace procedure lpmtest2   
  2. as    
  3.   cursor  youbiao is  select ename,sal,job from test where sal>1300;   
  4.   c_row youbiao%rowtype; --定义一个游标变量c_row ,该类型为游标youbiao中的一行数据类型   
  5. begin   
  6.   open youbiao;   
  7.   loop   
  8.     fetch youbiao into c_row;   
  9.     exit when youbiao%notfound;   
  10.     dbms_output.put_line('++:'||c_row.ename||':'||c_row.sal||':'||c_row.job);   
  11.   end loop;   
  12.   close youbiao;   
  13. end;  

代码

  1. create or replace procedure lpmtest3   
  2. as   
  3. cursor c_dept is select * from dept order by deptno;   
  4. cursor c_emp(p_dept varchar2) is select ename,sal from emp where deptno=p_dept order by ename;   
  5. r_dept c_dept%rowtype;   
  6. v_ename emp.ename%type;   
  7. v_sal   emp.sal%type;   
  8. v_totalsal emp.sal%type; --用来存每个部门所有员工的总工资   
  9. begin   
  10.   open c_dept;   
  11.   loop   
  12.     fetch c_dept into r_dept;   
  13.     exit when c_dept%notfound;   
  14.     dbms_output.put_line(r_dept.deptno||':'||r_dept.dname||'+++++++++++');   
  15.     v_totalsal:=0;   
  16.     open c_emp(r_dept.deptno);   
  17.     loop   
  18.       fetch c_emp into v_ename,v_sal;   
  19.       exit when c_emp%notfound;   
  20.       dbms_output.put_line('v_ename:'||v_ename||';'||'v_sal:'||v_sal);   
  21.       v_totalsal:=v_totalsal+v_sal;   
  22.      end loop;   
  23.      close c_emp;   
  24.      dbms_output.put_line('deptsaltotal:'||v_totalsal);   
  25.    end loop;   
  26.    close c_dept;   
  27. end;  

打印出来效果:

  1. 10:ACCOUNTING+++++++++++   
  2. v_ename:CLARK;v_sal:2450  
  3. v_ename:KING;v_sal:5000  
  4. v_ename:MILLER;v_sal:1300  
  5. deptsaltotal:8750  
  6. 20:RESEARCH+++++++++++   
  7. v_ename:ADAMS;v_sal:1100  
  8. v_ename:FORD;v_sal:3000  
  9. v_ename:JONES;v_sal:2975  
  10. v_ename:SCOTT;v_sal:3000  
  11. v_ename:SMITH;v_sal:800  
  12. deptsaltotal:10875  
  13. 30:SALES+++++++++++   
  14. v_ename:ALLEN;v_sal:1600  
  15. v_ename:BLAKE;v_sal:2850  
  16. v_ename:JAMES;v_sal:950  
  17. v_ename:MARTIN;v_sal:1250  
  18. v_ename:TURNER;v_sal:1500  
  19. v_ename:WARD;v_sal:1250  
  20. deptsaltotal:9400  
  21. 40:OPERATIONS+++++++++++   
  22. deptsaltotal:0  
更多Oracle相关信息见Oracle 专题页面 http://www.bkjia.com/topicnews.aspx?tid=12

相关内容