问题
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