Donnerstag, 1. September 2016

Check whether "something" is of number type

There are in the net several proposals for this. One is to write a proper PL/SQL function that tries to assign a given value to a number type variable. It returns TRUE if no exception is raised and catches the exception for the data type incompatibility and returns false.
However, within SQL this is inefficient as it will make a context switch for every row the function is applied to. Maybe the use of regular expressions with regexp_like is more efficient. However, it means that notation conventions have to be clear and met. In the following I will show a solution for following conventions.
  • A negative number is marked by a - as the first character
  • No white space character are allowed
  • No grouping separators allowed (for thousands and so on)
  • The decimal separator is a .
  • Fractions always need at least one digit after the decimal separator
  • Before decimal separator digits are optional, e.g. -0.12 equals -.12

Regular expression:
^-?[0-9]*([.][0-9]+)?$

SQL example:
select *
  from DUAL
 where regexp_like(
            '-.3',
            '^-?[0-9]*([.][0-9]+)?$')

Keine Kommentare:

Kommentar veröffentlichen