# The Teradata CHAR2HEXINT Function

Roland Wenzlofsky

June 5, 2014

minutes reading time

A recent blog by Roland Wenzlofsky introduced us to the CHAR2HEXINT function to extract coding table numbers for tokens.

If you found this a little off the scope of practical problems you have to deal with daily, let me tell you that precisely these functions helped us a lot in solving a real-world problem.

Assume that you receive a string that can contain any mix of characters or numbers. No instance prevents entries of special characters. Your task is to return the number part as a number if it truly is one and a default value otherwise.

We turned a given solution failing on special characters around by doing the desired extraction if every token of the substring of interest is a number.

Numeric tokens have an adjacent set of hexadecimal values. For anything not purely numeric as a whole, we default to -9 as agreed.

Note that shortcuts such as casting the substring â€™12 â€˜ (one-two-blank) to an integer provide false security.

Below the SQL that does the job:

``````SELECT
CASE WHEN CHAR2HEXINT( SUBSTR(â€šâ€˜1201â€™â€™, 2, 1) ) BETWEEN â€šâ€™030â€™â€™AND â€šâ€™039â€™â€™AND
CHAR2HEXINT( SUBSTR(â€š'1201â€˜' 3, 1) ) BETWEEN â€š'030â€˜'AND â€š'039â€˜'AND
CHAR2HEXINT( SUBSTR(â€š'1201â€˜', 4, 1) ) BETWEEN â€š'030â€˜'AND â€š'039â€˜'
THEN SUBSTR(â€š'1201â€˜', 2, 3)
ELSE -9
END``````

Alternative approaches I worked with in other DWH environments, such as regular expressions in Oracle SQL, do not come so handy in Teradata SQL.

Add this function to your arsenal of bug repellents and make your character operations less of a coding minefield.

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

You might also like