Conversion Functions – TRY_CONVERT()

I am going to carry on with my series of articles (tidbits) on type conversion functions available in the Transaction SQL (T-SQL) language.

One analogy of a data type conversion is apply the correct action to change the physical form of water (H2O). You can convert water to ice by cooling it. You can convert water to vapor by heating it. However, the chemical composition of water is still the same!

Information is stored in a database as rows in a table. Each field in a table is defined with a certain data type. The original designer of the database schema might not be aware of all potential uses of the stored information. Therefore, it is not uncommon as a developer to convert data from one type to another.

Today, I want to talk about how to use TRY_CONVERT function which takes a target data type, a source data value, and a optional style parameter. It returns the the source data value casted to the target data type. If the data type conversion is not allowed or any potential ERROR occurs, the function returns a NULL value.

The same examples are used again for researching this function.

The output from the TSQL example is shown below.

Unlike the CONVERT function, we end up with a NULL value when the arithmetic overflow occurs in the last statement.

In summary, I suggest using the TRY_CONVERT with the ISNULL function to prevent run time errors in your code.

Next time, I will be talking about the TRY_CAST function. This function was introduced in SQL Server 2012. Unlike its cousin, invalid casting of data results in a NULL value instead of an ERROR.

Related posts

Leave a Comment