最近针对一个多维度业务逻辑写了一个存储过程,遇到的问题留存以下:
1.声明的变量 长度不够导致,这个当时客户不提供debug权限,无法查到问题,可通过 plsql--》文件--》命令窗口 exec '存储过程名称';可以大致拿到错误原因,写一点测试一点 很难受。
2.拼接日期字符串时 老是出现关于单引号的问题。如汉字:v_sql :='selecct to_char(sysdate,'||'''yyyy'''||') from dual';
关于写between and 的 建议 使用变量拼接 如 v_begin ,v_end ; v_bt ;通过:select to_char(sysdate,'yyyy')||'0101' into v_begin from dual;
select to_char(sysdate,'yyyyMMdd') into v_end from dual;
v_bt:='between '||v_begin||' and '||v_end;
v_sql:= 'select * from test where operDate '||v_bt;
这样比较稳妥。
3.多条件组合查询 多重for循环 方式
以下以 按照 三位员工在 特定时间段 根据年龄 和 经手次数 多条件组合查询为例。
v_temp1 varchar2(1000);--此次如果sql语句较大 尽量大一点,但也有上限
v_temp2 varchar2(1000);
v_temp3 varchar2(2000);
v_sql varchar2(10000);
定义数组:
type a_array is array(10) of varchar2(20);
b_arr a_array;
type c_array is array(10) of varchar2(20);
d_arr c_array;
--赋值
b_arr:=a_array(1,2,3);---三个年龄段
d_arr:=c_array('A','AA','AAA');--三位员工
v_sql:= 'select id,name from test where time '||v_bt;---between and 动态语句
for i in 1..b_arr.count loop
-- dbms_output.put_line(b_arr(i));
--第一层变量赋值
if b_arr(i)=1 then v_temp1:=' and age=1'; elsif b_arr(i)=2 then v_temp1:=' and age=10';else v_temp1:=' and age=20'; end if;
--第二层循环
for ii in 1..d_arr.count loop
-- 第二层变量赋值
if d_arr(ii)='A' then v_temp2:=' and hand=2 )'; elsif d_arr(ii)='AA' then v_temp2:=' and hand=3) '; else v_temp2:=' and hand=6) '; end if;
v_temp3:=v_sql||v_temp1||v_temp2;-- 拼接整串
//执行动态sql 动态批量新增到新表test1
v_temp6:='insert into test1 (id,name) '||v_temp3;
execute immediate v_temp6; ---根据第一层循环,第二层循环 批量执行数据。类似 多条件组合查询
end loop;
end loop;