Reputation: 51
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
Upvotes: 5
Views: 19021
Reputation: 14886
Try...Catch is implemented in Postgres as a code block with exception handling. For this situation the error we're catching in can the resulting string from regex be converted to a numeric value. The following makes that conversion they converts back to a string to match the return value.
create or replace function test(v1 text)
returns text
language plpgsql
as
$$
declare
erro text ;
begin
begin -- try
erro:= (replace(regexp_replace(v1, '[^,.0-9]+', '', 'g'),',','.')::numeric)::text;
exception -- catch
when invalid_text_representation then -- error that can be handeled
erro = 'CONVERSION FAILED';
end ; -- try..catch
return erro;
end;
$$;
Upvotes: 4