2

I'm migrating an Oracle database to PostgreSQL, to transfer the tables I had no problem, however I'm having trouble transcribing a function for it to run in Postgres, below the function found in Oracle:

create or replace FUNCTION  "FN_HOUR_MINUTE" (P_HOUR IN NUMBER) 
RETURN NUMBER 
IS
  -- PL/SQL Specification
  V_RETORN                 NUMBER(4);
  -- Convert hour to minute
  -- PL/SQL Block
BEGIN
V_RETORN := 60*TO_NUMBER(SUBSTR(LTRIM(TO_CHAR(P_HOUR,'0000'),' ') ,1,2))+
                  TO_NUMBER(SUBSTR(LTRIM(TO_CHAR(P_HOUR, '0000'),' '), 3,2));

RETURN V_RETORN;
EXCEPTION
WHEN OTHERS THEN
       RETURN NULL ;
END;

I tried writing in postgres as follows:

CREATE OR REPLACE FUNCTION fn_hour_minute(p_hour in NUMERIC)
  RETURNS NUMERIC(4) AS $$
DECLARE
  v_retorn NUMERIC(4);
BEGIN
  v_retorn := 60*TO_NUMBER(SUBSTR(LTRIM(TO_CHAR(p_hour,'0000'),' ') ,1,2))+
                   TO_NUMBER(SUBSTR(LTRIM(TO_CHAR(p_hour, '0000'),' '), 3,2));
  RETURN v_retorn;
END;
$$ LANGUAGE plpgsql;

But gives an error that says the to_number function does not exist.

2
  • try TO_NUMBER(SUBSTR(LTRIM(TO_CHAR(p_hour,'0000'),' ') ,1,2), '0000') Also, why are you converting to character then to number? Commented Feb 28, 2018 at 20:36
  • It worked, thank you. I did not quite understand why he did these two conversions, the Oracle database was not made by me, but that function worked there in that way. Commented Feb 28, 2018 at 20:49

2 Answers 2

2

If you spread the expression into factors:

select TO_CHAR(1234,'0000'),
    ltrim(TO_CHAR(1234,'0000')),
    substr(ltrim(TO_CHAR(1234,'0000')),1,2),
    substr(ltrim(TO_CHAR(1234,'0000')),3,2)
from dual;

TO_CH LTRIM SU SU
----- ----- -- --
 1234 1234  12 34

you will see that this is just a very advanced way to calculate such an expression

60 * TRUNC( p_hour / 100 ) + p_hour % 100
Sign up to request clarification or add additional context in comments.

Comments

0

You forgot to include the formating for the TO_NUMBER section. Update the TO_NUMBER to TO_NUMBER(SUBSTR(LTRIM(TO_CHAR(p_hour,'0000'),' ') ,1,2), '0000') and it should work.

Comments

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.