Conversion Functions – TRY_CAST()

I am going to make headway on 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_CAST function which takes a source data value and a target data type as parameters. 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 CAST function, we end up with a NULL values when arithmetic overflow occurs in statement four or an invalid conversion happens in statement six.

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

Next time, I will be talking about the TRY_PARSE 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