希望能找到能与我共同进步的知心朋友!

pl/sql 小结

上一篇 / 下一篇  2012-10-30 14:23:53

结一下单行多列,单例多行和多行多列的写法:

1.单行多列:

  1. declare  
  2.        type xxx_type is record(  
  3.             my_sal emp.sal%type,--锚定数据类型  
  4.             my_num emp.empno%type  
  5.        );  
  6.        --声明一个记录的数据类型(记录类型是单行多列)  
  7.        xxx xxx_type;  
  8. begin  
  9.        select sal,empno into xxx from emp where emp.empno = 7369;--执行sql语句是赋值用into  
  10.        dbms_output.put_line(xxx.my_sal);--输出一行(需要先在sql下 set serveroutput on;)  
  11.        dbms_output.put_line(xxx.my_num);  
  12.        --这种方式大多用于自定义  
  13. end;  
  14. /  

还有一种是用表名+%rowtype来实现:

  1. declare  
  2.       xxx emp<SPAN style="COLOR: #ff0000">%rowtype</SPAN>;  
  3. begin  
  4.        select * into xxx from emp where emp.empno = 7369;  
  5.        dbms_output.put_line(xxx.sal);  
  6.        dbms_output.put_line(xxx.empno);  
  7.        dbms_output.put_line(xxx.ENAME);  
  8.        dbms_output.put_line(xxx.job);  
  9. end;--使用的时候<SPAN style="COLOR: #ff0000">成员个数,名称,类型必须和表货视图的列的个数,名称,类型完全相同</SPAN>  
  10. /  
2:单列多行

  1. declare  
  2.       type xxx_type is table of emp.sal%type  
  3.       index by binary_integer;--声明一个单列多行的结构  
  4.       xxx xxx_type;  
  5.       i number;  
  6. begin  
  7.        select sal <SPAN style="COLOR: #ff0000">bulk collect</SPAN> into xxx from emp where emp.deptno = 10;--给xxx批量赋值  
  8.        select count(sal) into i from emp where emp.deptno = 10;  
  9.        for j in 1..i loop  
  10.               dbms_output.put_line(xxx(j));  
  11.        end loop;  
  12. end;  
  13. /  

3:表结构(多行多列):

  1. declare  
  2.       type xxx_type is table of emp%rowtype  
  3.       index by binary_integer;--声明一个多列多行的结构  
  4.       xxx xxx_type;  
  5.       i number;  
  6. begin  
  7.        select * bulk collect into xxx from emp;--给xxx批量赋值  
  8.        select count(*) into i from emp ;  
  9.        for j in 1..i loop  
  10.               dbms_output.put_line(xxx(j).sal);  
  11.                dbms_output.put_line(xxx(j).ename);  
  12.                 dbms_output.put_line(xxx(j).job);  
  13.                  dbms_output.put_line(xxx(j).mgr);  
  14.        end loop;  
  15. end;  
  16. /  

异常的学习

题目如下 :请删除dept表中的deptno为10的这项并且emp表中的其他数据部受影响

  1. declare  
  2.   e exception;  
  3.   pragma exception_init(e,-02292);  
  4.   --自己定义非预处理异常并绑定异常  
  5. begin  
  6.     delete dept where deptno = 10;  
  7.     --出现异常  
  8. exception   
  9.     when e then   
  10.     --接收到异常  
  11.            --dbms_output.put_line('不能删除');  
  12.            update emp set deptno = null where deptno = 10;  
  13.            --将emp中的外键置为空  
  14.            delete dept where deptno = 10;  
  15.            --删除dept中的编号  
  16. end;  
  17. /  

TAG:

 

评分:0

我来说两句

Open Toolbar