Oracle to_char subquery in Trigger

拈花ヽ惹草 提交于 2019-12-13 03:35:33

问题


I have a table (Meeting) with date type attribute (MeetDate) and another varchar2 type attribute (WorkWeek). I'm trying to do an After trigger to fill in the WorkWeek field based on the MeetDate value using the to_char function. Tried the following codes separately and they compile without errors but when I try to insert a row with Null for WorkWeek, it gives me a 'mutating trigger/function may not see it' error. What am I doing wrong here? thanks in advance to any help.

--Code 1
Create or Replace Trigger Update_WorkWeek
After Insert On Meeting
For Each Row
Begin
Update Meeting
Set WorkWeek  = (Select to_char(:new.MeetDate, 'YYYY IW') From Dual)
Where MeetID = :new.MeetID;
End;
/
show Errors;

--Code 2
Create or Replace Trigger Update_WorkWeek
After Insert On Meeting
For Each Row
Begin
if :New.WorkWeek is Null then
Update Meeting
Set WorkWeek  = (Select to_char(:new.MeetDate, 'YYYY IW') From Dual)
Where MeetID = :new.MeetID;
End if;
End;
/
show Errors;

回答1:


You just want a trigger to change the value of a column before it gets inserted - and it's on the same row, so you don't need an UPDATE:

Create or Replace Trigger Update_WorkWeek
BEFORE Insert On Meeting
For Each Row
Begin
  :new.WorkWeek := to_char(:new.MeetDate, 'YYYY IW');
End;
/
show Errors;

You might want the column kept up-to-date if the MeetDate is changed, i.e.:

Create or Replace Trigger Update_WorkWeek
BEFORE Insert
    OR Update OF MeetDate
On Meeting
For Each Row
Begin
  :new.WorkWeek := to_char(:new.MeetDate, 'YYYY IW');
End;
/
show Errors;


来源:https://stackoverflow.com/questions/16311004/oracle-to-char-subquery-in-trigger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!