项目开发之存储过程发生的那些事

前言   

       以前在项目开发过程当中,须要有一步操做就是使用存储过程删除一系列相关的表,再使用mybatis调用该存储过程,输入参数为家人帐号,类型为String,数据库表结构中,该帐号字段类型为varchar2,再实操的过程当中,没有发生错误,多是输入参数虽然传入的是String类型,可是该帐号内容所有为数字,由于在执行过程当中就报“ORA-01722: 无效数字”异常了。         

缘由分析

         输入参数虽然是字符串类型,可是内容均为数字,在执行存储过程字符串拼接时,若是是使用“||”符号进行拼接,那么拼接后的sql是没有单引号的,也就是好比存储过程当中某条语句:execu_sql := 'delete from userinfo where account = ' ||account;(execu_sql为在存储过程定义的变量,为varchar(2000),":="为赋值操做,至关于把这条sql赋值给execu_sql这个表变量进行保存),可是执行完成后,execu_sql这个变量内容为:"delete from userinfo where account = XXXXXX",咱们知道,把这个sql运行,确定会报无效数字异常的,所以异常就是这样出现的,由于oracle有隐式转换机制,若是你传入的虽然是String类型的变量,可是若是变量的内容所有都会数字,那么oracle默认会将该String类型变量转化为数字,那么运行时就会报错了。

解决方案

        那么咱们在实操的过程当中就要动态的拼接单引号了,可使用ASCII 编码,单引号的ASCII 编码我39,那么存储过程sql能够这样写:execu_sql := 'delete from userinfo where account = '||chr(39)||account||chr(39);这样就不会出错了。

 

loop循环使用

       loop循环中能够循环调用存储过程而不会报错,例如:

     --循环建立明日的表
     loop
   --抽取方法,检查今天的表有无建立,若是没有就建立
   create_gps_day_table(current_datetime);
   
   --抽取方法,检查今天表序列是否建立,若是没有就建立
   create_gps_day_seq(current_datetime);
   
   current_datetime := current_datetime+1;
   --当中间天数小于结束月份天数跳出循环
    exit when current_datetime>end_datetime;
    end loop; sql

    可是若是loop循环中循环执行多条sql操做,则循环会失效,例如:

     loop    
       execu_sql := 'alter table '||table_names||' add(datas clob)';
       execute immediate execu_sql;
      
       execu_sql := 'update '||table_names||' set datas = data';
       execute immediate execu_sql;
   
       execu_sql := 'alter table '||table_names||' drop column data'; 
       execute immediate execu_sql;
   
       execu_sql := 'alter table '||table_names||' rename column datas to data';
       execute immediate execu_sql;
   
       start_datetime := start_datetime+1;
   
       exit when start_datetime>current_datetime;
     end loop;  数据库

     或者一条存储过程当中写多个循环,而且循环中执行一条sql操做,则第一条循环能成功,然后续循环均报:

ORA-00942:表或视图不存在错误。例如:

     loop    
       table_names := 'tb_app_time_'||start_datetime;
 
       execu_sql := 'alter table '||table_names||' add(datas clob)';
       execute immediate execu_sql;
   
       start_datetime := start_datetime + 1;
   
       exit when start_datetime>end_datetime;
     end loop;  
 
      loop          
       table_names := 'tb_app_time_'||start_datetime;
   
       execu_sql := 'update '||table_names||' set datas = data';
       execute immediate execu_sql;
   
       start_datetime := start_datetime+1;
   
       exit when start_datetime>end_datetime;
     end loop; mybatis

相关文章
相关标签/搜索