0

I have a problem when converting VARCHAR2 to Number in Oracle SQL.

My VARCHAR2 has the following characteristic: 0.000

For example: the value of Campo1 is 18.123 (with a .)

But I get an error:

  1. 00000 - "invalid number"

when trying to convert:

SELECT SUM(CAST(Campo1 AS NUMERIC)) AS VOLUME
FROM TESTE_NUMBER
WHERE Timestamp = '18/09/2020'

Is it possible to convert that string?

Thanks

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

2 Answers2

1

You can check that it looks like a number, first. For a non-negative:

select sum(case when regexp_like(campo1, '^[0-9]+[.]?[0-9]*$')
                the to_number(campo1)
           end)
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

Yes, if you remove space:

SELECT SUM(CAST(REPLACE(Campo1, ' ') AS NUMERIC)) AS VOLUME
FROM TESTE_NUMBER
where Timestamp = '18/09/2020';

'1722. 0000' should be '1722.0000'.


Using safe conversion “Safe” TO_NUMBER() will default faulty values to 0:

SELECT SUM(CAST(Campo1 AS NUMERIC DEFAULT 0 ON CONVERSION ERROR)) AS VOLUME
FROM TESTE_NUMBER
where Timestamp = '18/09/2020';

db<>fiddle demo

Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
  • Thanks for answering me, Lukasz. But continues with the same error inserting the select that you wrote :/ – Jefferson Sep 21 '20 at 15:41