I have a students table in my Oracle database which has a field called RECORD_NUMBER. This field is 8 characters long and I want to create a trigger to pad the left part out with 0s as it’s inserted. This is what I have so far:
create or replace
TRIGGER STUDENTS_RECORD_NUMBER_TRG
BEFORE INSERT OR UPDATE OF RECORD_NUMBER ON TBL_STUDENTS
FOR EACH ROW
BEGIN
WHILE length(:new.RECORD_NUMBER) < 9
LOOP
:new.RECORD_NUMBER := LPAD(:new.RECORD_NUMBER,8,'0');
END LOOP;
NULL;
END;
However, when I try to insert a row the database connection locks up and I have to restart Oracle to use it again. Is it possible that this trigger is causing an infinite loop?
If
record_numberis avarchar2(8), thenlength(:new.record_number)will always be less than 9 and your loop will iterate endlessly. But you don’t need a loop here, just callLPADThis assumes, of course, that it really makes sense to pad the data that is physically stored in the database rather than doing something like applying the
LPADin a view layer. Generally, I would expect that you’d be better served putting this sort of presentation logic in a view since views are great for implementing presentation logic. But this trigger should do what you’ve asked.