1

I have a table with many records and it continues to grow:

  table T_A
  { 
    total varchar2(10),
    total number
  }

The "total" field composed with 5 numbers and 1 character, e.g. "12345p", the character is either "p" or "N".

Now, I want to write a trigger to convert existing "total" to numbers and store them in "total_num". furthermore, if there are inserting or updating operations, it can automatically finishes this conversion, and it must satisfy the following condition:

if the character is "p", the number is positive, e.g. "12345p" converts to "12345", otherwise, the number is negative. e.g. "12345N" converts to "-12345".

How to write this trigger?

1 Answer 1

6

Try this

(not tested as I don't have an oracle connection at the moment)

  CREATE OR REPLACE TRIGGER trg_ta_totals
  BEFORE INSERT OR UPDATE ON T_A
  FOR EACH ROW

    DECLARE
        vnum number;
    BEGIN

    IF instr(:NEW.total,'p') > 0 THEN
       vnum:=TO_NUMBER(SUBSTR(:NEW.total,0,LENGTH(:NEW.total)-1));     
    ELSIF instr(:NEW.total,'N') > 0 THEN
       vnum:=TO_NUMBER(SUBSTR(:NEW.total,0,LENGTH(:NEW.total)-1))*-1;
    END IF; 

    :NEW.total_num := vnum; 

    END;
Sign up to request clarification or add additional context in comments.

4 Comments

good for structure... OP may wish to do other checks if his data is dirtier than he thinks.. :)
Note that the OP's posted code has a lower case p and an upper case N: the instr() checks need to match the case.
+1 A subjective sidenote though: I find "IF :NEW.total like '%p%' THEN" much more in line with your intentions than using the INSTR operator.
It's exactly what I wanted! Thanks everybody.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.