I need to clear (remove special characters) and convert a text to a numeric. But, if it is not possible to perform the conversion, I need to save the error in a variable to later, along with other errors, be inserted into a tuple of a table.
CREATE OR REPLACE FUNCTION TEST(V1 TEXT, OUT ERRO TEXT)
RETURNS TEXT
LANGUAGE plpgsql
AS
$$
DECLARE
V2 NUMERIC;
MSG TEXT;
BEGIN
--"TRY"
V2 := REPLACE(REGEXP_REPLACE(V1, '[^,.0-9]+', '', 'g'),',','.');
--"CATCH"
MSG = 'CONVERSION FAILED';
SELECT MSG INTO ERRO;
END;
$$;
SELECT * FROM TEST('65,^%F,5');
--EXPECTED: 'CONVERSION FAILED'
SELECT * FROM TEST('65^%F,5');
--EXPECTED: 65.5