`

存储过程常用技巧3

阅读更多

3.4 select into不可乎视的问题
我们知道在pl/sql中要想从数据表中向变量赋值,需要使用select into 子句。
但是它会带动来一些问题,如果查询没有记录时,会抛出no_data_found异常。
如果有多条记录时,会抛出too_many_rows异常。
这个是比较糟糕的。一旦抛出了异常,就会让过程中断。特别是no_data_found这种异常,没有严重到要让程序中断的地步,可以完全交给由程序进行处理。

Java代码 复制代码
  1. create or replace procedure procexception(p varchar2)   
  2. as    
  3.   v_postype varchar2(20);   
  4. begin   
  5.    select pos_type into v_postype from pos_type_tbl where 1=0;   
  6.     dbms_output.put_line(v_postype);   
  7. end;   
  8.       
create or replace procedure procexception(p varchar2)
as 
  v_postype varchar2(20);
begin
   select pos_type into v_postype from pos_type_tbl where 1=0;
    dbms_output.put_line(v_postype);
end;
	

执行这个过程

Java代码 复制代码
  1. SQL> exec procexception('a');   
  2. 报错   
  3. ORA-01403: no data found   
  4. ORA-06512: at "LIFEMAN.PROCEXCEPTION", line 6  
  5. ORA-06512: at line 1  
SQL> exec procexception('a');
报错
ORA-01403: no data found
ORA-06512: at "LIFEMAN.PROCEXCEPTION", line 6
ORA-06512: at line 1


处理这个有三个办法
1. 直接加上异常处理。

Java代码 复制代码
  1. create or replace procedure procexception(p varchar2)   
  2. as    
  3.   v_postype varchar2(20);   
  4.      
  5. begin   
  6.    select pos_type into v_postype from pos_type_tbl where 1=0;   
  7.     dbms_output.put_line(v_postype);   
  8. exception    
  9.   when no_data_found then   
  10.     dbms_output.put_line('没找到数据');   
  11. end;  
create or replace procedure procexception(p varchar2)
as 
  v_postype varchar2(20);
  
begin
   select pos_type into v_postype from pos_type_tbl where 1=0;
    dbms_output.put_line(v_postype);
exception 
  when no_data_found then
    dbms_output.put_line('没找到数据');
end;

这样做换汤不换药,程序仍然被中断。可能这样不是我们所想要的。
2. select into做为一个独立的块,在这个块中进行异常处理

Java代码 复制代码
  1. create or replace procedure procexception(p varchar2)   
  2. as    
  3.   v_postype varchar2(20);   
  4.      
  5. begin   
  6.   begin   
  7.    select pos_type into v_postype from pos_type_tbl where 1=0;   
  8.     dbms_output.put_line(v_postype);   
  9.  exception    
  10.   when no_data_found then   
  11.     v_postype := '';   
  12.   end;   
  13.   dbms_output.put_line(v_postype);   
  14. end;  
create or replace procedure procexception(p varchar2)
as 
  v_postype varchar2(20);
  
begin
  begin
   select pos_type into v_postype from pos_type_tbl where 1=0;
    dbms_output.put_line(v_postype);
 exception 
  when no_data_found then
    v_postype := '';
  end;
  dbms_output.put_line(v_postype);
end;

这是一种比较好的处理方式了。不会因为这个异常而引起程序中断。
3.使用游标

Java代码 复制代码
  1. create or replace procedure procexception(p varchar2)   
  2. as    
  3.   v_postype varchar2(20);   
  4.   cursor c_postype is select pos_type  from pos_type_tbl where 1=0;   
  5. begin   
  6.   open c_postype;   
  7.     fetch c_postype into v_postype;   
  8.   close c_postype;   
  9.   dbms_output.put_line(v_postype);   
  10. end;  
create or replace procedure procexception(p varchar2)
as 
  v_postype varchar2(20);
  cursor c_postype is select pos_type  from pos_type_tbl where 1=0;
begin
  open c_postype;
    fetch c_postype into v_postype;
  close c_postype;
  dbms_output.put_line(v_postype);
end;

这样就完全的避免了no_data_found异常。完全交由程序员来进行控制了。

第二种情况是too_many_rows 异常的问题。
Too_many_rows 这个问题比起no_data_found要复杂一些。
给一个变量赋值时,但是查询结果有多个记录。
处理这种问题也有两种情况:
1. 多条数据是可以接受的,也就是说从结果集中随便取一个值就行。这种情况应该很极端了吧,如果出现这种情况,也说明了程序的严谨性存在问题。
2. 多条数据是不可以被接受的,在这种情况肯定是程序的逻辑出了问题,也说是说原来根本就不会想到它会产生多条记录。
对于第一种情况,就必须采用游标来处理,而对于第二种情况就必须使用内部块来处理,重新抛出异常。
多条数据可以接受,随便取一条,这个跟no_data_found的处理方式一样,使用游标。
我这里仅说第二种情况,不可接受多条数据,但是不要忘了处理no_data_found哦。这就不能使用游标了,必须使用内部块。

Java代码 复制代码
  1. create or replace procedure procexception2(p varchar2)   
  2. as    
  3.   v_postype varchar2(20);   
  4.     
  5. begin   
  6.   begin   
  7.     select pos_type into v_postype from pos_type_tbl where rownum < 5;   
  8.   exception   
  9.     when no_data_found then   
  10.       v_postype :=null;   
  11.     when too_many_rows then   
  12.       raise_application_error(-20000,'对v_postype赋值时,找到多条数据');   
  13.   end;   
  14.  dbms_output.put_line(v_postype);   
  15. end;  
create or replace procedure procexception2(p varchar2)
as 
  v_postype varchar2(20);
 
begin
  begin
    select pos_type into v_postype from pos_type_tbl where rownum < 5;
  exception
    when no_data_found then
      v_postype :=null;
    when too_many_rows then
      raise_application_error(-20000,'对v_postype赋值时,找到多条数据');
  end;
 dbms_output.put_line(v_postype);
end;

需要注意的是一定要加上对no_data_found的处理,对出现多条记录的情况则继续抛出异常,让上一层来处理。
总之对于select into的语句需要注意这两种情况了。需要妥当处理啊。

3.5 在存储过程中返回结果集
我们使用存储过程都是返回值都是单一的,有时我们需要从过程中返回一个集合。即多条数据。这有几种解决方案。比较简单的做法是写临时表,但是这种做法不灵活。而且维护麻烦。我们可以使用嵌套表来实现.没有一个集合类型能够与java的jdbc类型匹配。这就是对象与关系数据库的阻抗吧。数据库的对象并不能够完全转换为编程语言的对象,还必须使用关系数据库的处理方式。

Java代码 复制代码
  1. create or replace package procpkg is   
  2.    type refcursor is ref cursor;   
  3.    procedure procrefcursor(p varchar2, p_ref_postypeList  out refcursor);   
  4. end procpkg;   
  5.   
  6. create or replace package body procpkg is   
  7.   procedure procrefcursor(p varchar2, p_ref_postypeList out  refcursor)   
  8.   is   
  9.     v_posTypeList PosTypeTable;   
  10.   begin   
  11.     v_posTypeList :=PosTypeTable();--初始化嵌套表   
  12.     v_posTypeList.extend;   
  13.     v_posTypeList(1) := PosType('A001','客户资料变更');   
  14.     v_posTypeList.extend;   
  15.     v_posTypeList(2) := PosType('A002','团体资料变更');   
  16.     v_posTypeList.extend;   
  17.     v_posTypeList(3) := PosType('A003','受益人变更');   
  18.     v_posTypeList.extend;   
  19.     v_posTypeList(4) := PosType('A004','续期交费方式变更');   
  20.     open p_ref_postypeList for  select * from table(cast (v_posTypeList as PosTypeTable));   
  21.   end;   
  22. end procpkg;  
create or replace package procpkg is
   type refcursor is ref cursor;
   procedure procrefcursor(p varchar2, p_ref_postypeList  out refcursor);
end procpkg;

create or replace package body procpkg is
  procedure procrefcursor(p varchar2, p_ref_postypeList out  refcursor)
  is
    v_posTypeList PosTypeTable;
  begin
    v_posTypeList :=PosTypeTable();--初始化嵌套表
    v_posTypeList.extend;
    v_posTypeList(1) := PosType('A001','客户资料变更');
    v_posTypeList.extend;
    v_posTypeList(2) := PosType('A002','团体资料变更');
    v_posTypeList.extend;
    v_posTypeList(3) := PosType('A003','受益人变更');
    v_posTypeList.extend;
    v_posTypeList(4) := PosType('A004','续期交费方式变更');
    open p_ref_postypeList for  select * from table(cast (v_posTypeList as PosTypeTable));
  end;
end procpkg;


在包头中定义了一个游标变量,并把它作为存储过程的参数类型。
在存储过程中定义了一个嵌套表变量,对数据写进嵌套表中,然后把嵌套表进行类型转换为table,游标变量从这个嵌套表中进行查询。外部程序调用这个游标。
所以这个过程需要定义两个类型。

Java代码 复制代码
  1. create or replace type PosType as Object (   
  2.   posType varchar2(20),   
  3.   description varchar2(50)   
  4. );  
create or replace type PosType as Object (
  posType varchar2(20),
  description varchar2(50)
);

create or replace type PosTypeTable is table of PosType;
需要注意,这两个类型不能定义在包头中,必须单独定义,这样java层才能使用。

在外部通过pl/sql来调用这个过程非常简单。

Java代码 复制代码
  1. set serveroutput on;   
  2. declare    
  3.   type refcursor is ref cursor;   
  4.   v_ref_postype refcursor;   
  5.   v_postype varchar2(20);   
  6.   v_desc varchar2(50);   
  7. begin   
  8.   procpkg.procrefcursor('a',v_ref_postype);   
  9.   loop   
  10.     fetch  v_ref_postype into v_postype,v_desc;   
  11.     exit when v_ref_postype%notfound;   
  12.     dbms_output.put_line('posType:'|| v_postype || ';description:' || v_desc);   
  13.   end loop;   
  14. end;  
set serveroutput on;
declare 
  type refcursor is ref cursor;
  v_ref_postype refcursor;
  v_postype varchar2(20);
  v_desc varchar2(50);
begin
  procpkg.procrefcursor('a',v_ref_postype);
  loop
    fetch  v_ref_postype into v_postype,v_desc;
    exit when v_ref_postype%notfound;
    dbms_output.put_line('posType:'|| v_postype || ';description:' || v_desc);
  end loop;
end;


注意:对于游标变量,不能使用for循环来处理。因为for循环会隐式的执行open动作。而通过open for来打开的游标%isopen是为true的。也就是默认打开的。Open一个已经open的游标是错误的。所以不能使用for循环来处理游标变量。

我们主要讨论的是如何通过jdbc调用来处理这个输出参数。

Java代码 复制代码
  1. conn = this.getDataSource().getConnection();   
  2. CallableStatement call = conn.prepareCall("{call procpkg.procrefcursor(?,?)}");   
  3. call.setString(1null);   
  4. call.registerOutParameter(2, OracleTypes.CURSOR);   
  5. call.execute();   
  6. ResultSet rsResult = (ResultSet) call.getObject(2);   
  7. while (rsResult.next()) {   
  8.   String posType = rsResult.getString("posType");   
  9.   String description = rsResult.getString("description");   
  10.   ......   
  11. }  
conn = this.getDataSource().getConnection();
CallableStatement call = conn.prepareCall("{call procpkg.procrefcursor(?,?)}");
call.setString(1, null);
call.registerOutParameter(2, OracleTypes.CURSOR);
call.execute();
ResultSet rsResult = (ResultSet) call.getObject(2);
while (rsResult.next()) {
  String posType = rsResult.getString("posType");
  String description = rsResult.getString("description");
  ......
}


这就是jdbc的处理方法。

Ibatis处理方法:
1.参数配置

Java代码 复制代码
  1. <parameterMap id="PosTypeMAP" class="java.util.Map">    
  2.  <parameter property="p" jdbcType="VARCHAR" javaType="java.lang.String" />    
  3.  <parameter property="p_ref_postypeList" jdbcType="ORACLECURSOR" javaType="java.sql.ResultSet" mode="OUT" typeHandler="com.palic.elis.pos.dayprocset.integration.dao.impl.CursorHandlerCallBack" />    
  4. </parameterMap>   
  5.   
  6. 2.调用过程   
  7.   <procedure id ="procrefcursor" parameterMap ="PosTypeMAP">   
  8.       {call procpkg.procrefcursor(?,?)}   
  9.   </procedure>   
  10.   
  11. 3.定义自己的处理器   
  12.   public class CursorHandlerCallBack implements TypeHandler{   
  13.     public Object getResult(CallableStatement cs, int index) throws SQLException {   
  14.         ResultSet rs = (ResultSet)cs.getObject(index);   
  15.         List result = new ArrayList();   
  16.         while(rs.next()) {   
  17.             String postype =rs.getString(1);   
  18.             String description = rs.getString(2);   
  19.             CodeTableItemDTO posTypeItem = new CodeTableItemDTO();   
  20.             posTypeItem.setCode(postype);   
  21.             posTypeItem.setDescription(description);   
  22.             result.add(posTypeItem);   
  23.         }   
  24.         return result;   
  25.     }   
  26.   
  27.   
  28.   
  29. 4. dao方法   
  30.     public List procPostype() {   
  31.         String p = "";   
  32.         Map para = new HashMap();   
  33.         para.put("p",p);   
  34.         para.put("p_ref_postypeList",null);   
  35.          this.getSqlMapClientTemplate().queryForList("pos_dayprocset.procrefcursor",  para);   
  36.          return (List)para.get("p_ref_postypeList");   
  37.     }  
<parameterMap id="PosTypeMAP" class="java.util.Map"> 
 <parameter property="p" jdbcType="VARCHAR" javaType="java.lang.String" /> 
 <parameter property="p_ref_postypeList" jdbcType="ORACLECURSOR" javaType="java.sql.ResultSet" mode="OUT" typeHandler="com.palic.elis.pos.dayprocset.integration.dao.impl.CursorHandlerCallBack" /> 
</parameterMap>

2.调用过程
  <procedure id ="procrefcursor" parameterMap ="PosTypeMAP">
      {call procpkg.procrefcursor(?,?)}
  </procedure>

3.定义自己的处理器
  public class CursorHandlerCallBack implements TypeHandler{
	public Object getResult(CallableStatement cs, int index) throws SQLException {
		ResultSet rs = (ResultSet)cs.getObject(index);
        List result = new ArrayList();
		while(rs.next()) {
			String postype =rs.getString(1);
			String description = rs.getString(2);
			CodeTableItemDTO posTypeItem = new CodeTableItemDTO();
			posTypeItem.setCode(postype);
			posTypeItem.setDescription(description);
			result.add(posTypeItem);
		}
		return result;
	}



4. dao方法
	public List procPostype() {
		String p = "";
		Map para = new HashMap();
		para.put("p",p);
		para.put("p_ref_postypeList",null);
		 this.getSqlMapClientTemplate().queryForList("pos_dayprocset.procrefcursor",  para);
		 return (List)para.get("p_ref_postypeList");
	}


这个跟jdbc的方式非常的相似.
我们使用的是ibatis的2.0版本,比较麻烦。
如果是使用2.2以上版本就非常简单的。
因为可以在parameterMap中定义一个resultMap.这样就无需要自己定义处理器了。
可以从分析2.0和2.0的dtd文件知道。

分享到:
评论
2 楼 jeff06143132 2010-08-17  
支持,努力,加油。谢谢
1 楼 jeff06143132 2010-08-17  
你好,请问我可以转载你这篇文章吗? 对我比较有用。

相关推荐

    oracle存储过程常用技巧

    Oracle存储过程常用技巧 Oracle存储过程是一种强大的数据库对象,它可以帮助开发者简化复杂的业务逻辑,并提高数据库的安全性和性能。在 Oracle 中,存储过程是一种特殊的 PL/SQL 程序,它可以接受输入参数,执行...

    oracle存储过程常用的一些功能

    介绍oracle存储过程的常用使用技巧

    oracle存储过程常用的技巧(详)

    存储过程是在大型数据库系统中存储过程在数据库中经过第一次编译后就不需要再次编译,用户通过指定存储过程的名字并给出参数来,通过本篇文章带领大家去学习oracle存储过程常用的技巧,感兴趣的朋友一起来学习吧

    Windows API常用技巧汇编

    《Windows API常用技巧汇编》是一本专注于Windows操作系统编程技术的资源集合,它可能包含了光盘形式的视频讲座,旨在帮助开发者深入理解和掌握Windows API的使用。Windows API是微软为开发者提供的一个接口,通过...

    asp.net利用存储过程分页代码

    - 对于其他页,存储过程将采用一种巧妙的技巧:它先选取前`(@PageIndex - 1) * @PageSize`个满足条件的记录,找到其中`@fldName`字段的最大或最小值,然后选取`@PageSize`条大于(升序)或小于(降序)这个值的记录...

    DB2存储过程入门实例

    3. 使用CREATE PROCEDURE语句声明并创建存储过程。 示例: ```sql CREATE PROCEDURE my_proc (IN param1 INT, OUT param2 VARCHAR(50)) BEGIN SELECT column1 INTO param2 FROM my_table WHERE id = param1; END@ ...

    VB常用技巧合集

    VB常用技巧合集 chm全集,比如ActiveX .Exe .Dll Server的多执行绪,ADO/DAO Bolb资料的存取,ADO/RDO Concurrency for SQL 的比较,ADO 连线的其他注意事项,ADO阶层式资料库表达,ADO设定独占性的资料库,Check两...

    C#调用存储过程

    3. **C#调用有参数存储过程** 对于有参数的存储过程,你需要在`SqlCommand`对象中添加`SqlParameter`对象来传递参数值。每个参数包括名称(对应存储过程中的参数名)、方向(输入、输出或输入/输出)和值。以下是一...

    MSSQL 万能查询存储过程

    可能包含的存储过程可能涉及各种查询技巧,如联接、子查询、聚合函数、排序、分组等,以满足不同类型的查询需求。 在文件名称“查询存储过程.txt”中,我们可以推测这是文档格式,可能包含这些存储过程的详细说明、...

    Sybase数据库的存储过程性能优化.pdf

    存储过程是数据库管理中常用的一种编程手段,它允许开发者编写复杂的SQL语句和控制流程,以实现特定的业务逻辑。然而,游标在存储过程中的使用虽然方便,却往往会导致性能下降。 文章指出,游标是一种逐行处理数据...

    VBA常用技巧解析

    袁竹平老师的"VBA常用技巧解析"系列教程,显然是为了帮助用户深入理解和掌握VBA的核心技巧。下面,我们将对这个系列可能涵盖的一些关键知识点进行详细阐述。 首先,基础语法是学习VBA的起点。这包括变量的声明与...

    效率高的分页存储过程实现的分页

    在IT行业中,分页是一种非常常见的数据展示技术,特别是在网页应用和数据库管理中。它能够有效地处理大量数据,避免一次性加载所有...合理设计和使用存储过程是数据库开发中的重要技巧,尤其是在处理大数据量的场景下。

    VBA常用技巧电子书

    这份“VBA常用技巧电子书”显然是为Excel初学者或对VBA有一定了解但希望提升技能的用户提供的一份宝贵资源。以下是基于这个主题的详细知识点: 1. **VBA基础**:学习VBA首先需要了解基本的编程概念,如变量、数据...

    FPGA设计的四种常用思想和技巧

    流水线操作是一种常用的数据处理技巧,通过将数据处理过程分解为多个阶段,每个阶段完成特定的数据处理任务,实现高速数据流的处理。流水线操作可以应用于各种数据处理场景,例如在数字信号处理中,将信号处理过程...

    sql常用语句集锦 查询技巧

    在SQL Server中,可以使用`bcp`命令行工具或`xp_cmdshell`扩展存储过程将查询结果导出为文本文件。 以上知识点涵盖了SQL中的基本查询技巧和高级用法,对于日常的数据操作和分析非常实用。通过深入理解和掌握这些...

    EBS FORM开发常用技巧

    本文将深入探讨"EBS FORM开发常用技巧",这些技巧可以帮助开发者更高效、更专业地进行Oracle Forms的开发工作。 一、表单设计与布局 1. **模块化设计**:在开发大型表单时,采用组件化和模块化的设计方法,将复杂...

    常用修改电脑参数小技巧

    本篇文章将深入探讨一些常用的电脑参数修改技巧,帮助你更好地理解和掌握这些实用技能。 1. **系统性能设置**:在“控制面板”或“设置”中,你可以找到“系统”选项,这里可以调整电脑的性能模式。例如,如果你...

    sql数据库存储过程

    SQL数据库存储过程是数据库管理系统中一个非常重要的特性,主要用于封装一系列复杂的SQL操作,提升数据库的性能、可维护性和...理解并熟练掌握存储过程的创建、调用和优化技巧,对于任何数据库开发者来说都至关重要。

Global site tag (gtag.js) - Google Analytics