[目录]
参考
开发环境
| 名称 | 版本 |
|---|---|
| 操作系统 | Windows 10 X64 |
| Oracel | win64_11gR2_database |
| PLSQL Developer | 11.0.4.1788(64 bit)01.179332 - Unlimited user license |
测试表-test_v_hwhao1
测试数据
问题描述
在 Oracle-实际返回的行数超出请求的行数 这个例子中,我还遇到另外一个问题
declarevar_costcenter_name varchar2(255);var_check_account_code varchar2(255);var_check_account_name varchar2(255);beginselect COSTCENTER_NAME,CHECK_ACCOUNT_CODE,CHECK_ACCOUNT_NAME into var_costcenter_name,var_check_account_code,var_check_account_namefrom Test_Luomawhere COSTCENTER_CODE = 'BZ505' and rownum=1 ;--打印调用结果dbms_output.put_line(var_costcenter_name || var_check_account_code || var_check_account_name);end;
如果 select 语句没有查询到数据,也是会报错的。
这里针对这个问题使用测试表 test_v_hwhao1 进行分析和测试。
异常处理
写一个脚本,循环表 test_v_hwhao1,输出大于 7 的 NO 字段
beginfor item in (select NO from test_v_hwhao1 order by No)loopif item.NO > 7 thendbms_output.put_line(item.NO);end if;end loop;--commit;--添加一个异常处理当没有数据的时候赋一个默认值exceptionwhen NO_DATA_FOUND thendbms_output.put_line('没找到数据');when others thendbms_output.put_line('Others Exception');end;/
输出
1011Others Exception
根据测试数据,其实应该输出的是
101180
而且根据语法,exception 应该放在 end 之前
循环中的异常处理
根据 怎么在循环中处理异常oracle: Cursor a; for a_1 in a loop … exception … end loop 回答,我在 loop 中加了一个 begin end
beginfor item in (select NO from test_v_hwhao1 order by No)loopbeginif item.NO > 7 thendbms_output.put_line(item.NO);end if;--添加一个异常处理当没有数据的时候赋一个默认值exceptionwhen NO_DATA_FOUND thendbms_output.put_line('没找到数据');when others thendbms_output.put_line('Others Exception');end;end loop;end;/
输出
1011Others Exception89
更新(2019年11月13日17:44:29)
发现这个异常处理可以用在可能出错的任何地方,但是要包括在 begin end 中,例如
--rownum=1 避免查询出多条数据导致报错beginselect GENDER into var_genderfrom TEST1where STAFF_ID = item.STAFF_ID and rownum=1;--处理查询数据为空的情况exceptionwhen NO_DATA_FOUND thendbms_output.put_line('没找到性别数据,Period=' || item.PERIOD || ',staffId=' || item.STAFF_ID);when others thendbms_output.put_line('Others Exception');end;--rownum=1 避免查询出多条数据导致报错if length(item.PYCOSTC) > 0 thenbeginselect NAME into var_namefrom TEST2where COSTCENTER_CODE = item.PYCOSTC and rownum=1 and PERIOD = item.PERIOD;--处理查询数据为空的情况exceptionwhen NO_DATA_FOUND thendbms_output.put_line('没找到数据,Period=' || item.PERIOD || ',PYCOSTC=' || item.PYCOSTC);when others thendbms_output.put_line('Others Exception');end;end if;
自定义异常
declarel_error_code EXCEPTION;begindbms_output.put_line('1');Raise l_error_code;dbms_output.put_line('2');Exceptionwhen l_error_code Thendbms_output.put_line('自定义异常');when others thendbms_output.put_line('其它异常');end;
输出
1自定义异常