【问题标题】:Oracle: DML operation inside a query [duplicate]Oracle:查询中的 DML 操作 [重复]
【发布时间】:2013-07-27 03:59:59
【问题描述】:

我收到此错误:

cannot perform a DML operation inside a query

当我尝试执行查询时

select st_atten_up(1,7) from dual;

代码如下。

create or replace FUNCTION st_atten_up(stu_id IN student_info.id%type,app_mon IN student_attendence.month%type) 
RETURN NUMBER 
IS 
att1 NUMBER;
BEGIN SELECT ATTENDANCE into att1 FROM student_attendence 
WHERE student_attendence.id = stu_id and student_attendence.month = app_mon; 
att1 := att1 + 1;
UPDATE student_attendence SET ATTENDANCE = att1 
where id = stu_id and month = app_mon;
return att1;
END;

提前致谢。

【问题讨论】:

  • 在你的函数中使用 pragma autonomous_transaction; 使其可以从 select 语句中调用。

标签: oracle plsql oracle10g plsqldeveloper


【解决方案1】:

如果调用的函数已声明为PRAGMA AUTONOMOUS_TRANSACTION (Link),则从技术上讲,您可以在 select 内执行 DML。但是,出于多种原因(包括变异表、性能下降),从 SELECT 语句中执行 DML很少是个好主意。但是,要回答您的问题,您可以编写您的函数与PRAGMA:

create or replace FUNCTION st_atten_up(stu_id IN student_info.id%type,app_mon IN student_attendence.month%type) 
RETURN NUMBER 
IS
PRAGMA AUTONOMOUS_TRANSACTION;
att1 NUMBER;
BEGIN SELECT ATTENDANCE into att1 FROM student_attendence 
WHERE student_attendence.id = stu_id and student_attendence.month = app_mon; 
att1 := att1 + 1;
UPDATE student_attendence SET ATTENDANCE = att1 
where id = stu_id and month = app_mon;
return att1;
END;

【讨论】:

  • 很少代替从不... 在 SQL 语句中多次调用该函数会发生什么?学生最终达到 150% 的出勤率......
  • @wolf 谢谢它的工作。只是我需要添加“提交”以防止>>ORA-06519:检测到并回滚活动自主事务:
【解决方案2】:

如果函数本身具有 DML 操作,则不能在 DML 中调用函数。

在这里,您将尝试在 SELECT/UPDATE.. 中调用该函数,这就是它给出错误的原因。如果您想这样做,请创建一个程序。

【讨论】:

    猜你喜欢
    • 2019-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-11
    相关资源
    最近更新 更多