Skip to content
Advertisement

Is there an equivalent to TRY_CONVERT() in Oracle?

TRY_CONVERT() in T-SQL would return a value cast to the specified data type if the cast succeeded; otherwise it would return NULL.

Is there a similar function in ORACLE or a way to reproduce this behaviour?

Advertisement

Answer

If you’re not on Oracle 12.2 you can use a regex to determine if the value is valid before casting. For an integer (in the math sense, meaning optional sign, then one or more digits):

SELECT
  CASE WHEN REGEXP_LIKE(col, '^[-+]?[0-9]+$') THEN CAST(col AS NUMBER) END AS num
FROM myTable

This gives the same behavior as the Oracle 12.2 DEFAULT NULL ON CONVERSION ERROR.

For values other than integers the same approach applies, but the regexes get tougher.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement