在编写一个数据库函数时,方法实现需要查询后进行修改,出现ora-14551的错误
create or replace function fun_DxcBillSn(tabType integer,tabName varchar2,fieldStr varchar2)return integer is serialSn integer; maxVal integer; nowMonth varchar(20); begin --获取当前时间的月份-- select to_char(Sysdate,‘MM‘) into nowMonth from dual; --检查是否存在单号最大值 表名+ 类型 + 月份+字段 --- select COUNT(*) into maxVal from DXC_SYSSN where TABLENAME=tabName and BILLTYPE=tabType and MONTH=nowMonth and FIELD=fieldStr; --如果大于0 ,证明存在序号记录-- if maxVal >0 then --获取序号表的最大值 -- select MAXVAL into maxVal from DXC_SYSSN where TABLENAME=tabName and BILLTYPE=tabType and MONTH=nowMonth and FIELD=fieldStr; --获取序号ID值 -- serialSn:= maxVal+1; --更新序号表记录的值 -- update DXC_SYSSN set MAXVAL=serialSn where TABLENAME=tabName and BILLTYPE=tabType and MONTH=nowMonth and FIELD=fieldStr; --如果小于等于0 ,证明不存在记录 else --删除旧数据记录 delete from DXC_SYSSN where TABLENAME=tabName and BILLTYPE=tabType and FIELD=fieldStr; -- 返回序号的ID -- serialSn:=1; --添加新的数据记录 insert into DXC_SYSSN(TABLENAME,BILLTYPE,MONTH,FIELD,MAXVAL) values(tabName,tabType,nowMonth,fieldStr,serialSn); end if; return serialSn; end;
解决方法
在声明函数之前加上pragma autonomous_transaction ,在执行DML语句后Commit;
经过如上修改后的函数如下
create or replace function fun_DxcBillSn(tabType integer,tabName varchar2,fieldStr varchar2)return integer is --开启自治事务(解决Oracle ORA-14551: 无法在查询中执行 DML 操作的问题)-- pragma autonomous_transaction; serialSn integer; maxVal integer; nowMonth varchar(20); begin --获取当前时间的月份-- select to_char(Sysdate,‘MM‘) into nowMonth from dual; --检查是否存在单号最大值 表名+ 类型 + 月份+字段 --- select COUNT(*) into maxVal from DXC_SYSSN where TABLENAME=tabName and BILLTYPE=tabType and MONTH=nowMonth and FIELD=fieldStr; --如果大于0 ,证明存在序号记录-- if maxVal >0 then --获取序号表的最大值 -- select MAXVAL into maxVal from DXC_SYSSN where TABLENAME=tabName and BILLTYPE=tabType and MONTH=nowMonth and FIELD=fieldStr; --获取序号ID值 -- serialSn:= maxVal+1; --更新序号表记录的值 -- update DXC_SYSSN set MAXVAL=serialSn where TABLENAME=tabName and BILLTYPE=tabType and MONTH=nowMonth and FIELD=fieldStr; --如果小于等于0 ,证明不存在记录 else --删除旧数据记录 delete from DXC_SYSSN where TABLENAME=tabName and BILLTYPE=tabType and FIELD=fieldStr; -- 返回序号的ID -- serialSn:=1; --添加新的数据记录 insert into DXC_SYSSN(TABLENAME,BILLTYPE,MONTH,FIELD,MAXVAL) values(tabName,tabType,nowMonth,fieldStr,serialSn); end if; commit; -- 提交事务 return serialSn; end;
参考来源:https://www.linuxidc.com/Linux/2013-06/86713.htm
原文地址:https://www.cnblogs.com/xielong/p/10716586.html
时间: 2024-11-03 12:46:58