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.
1 2 3 4 5 6 7 8 9 10 11 12 |
-- -- Format expressions using TRY_CONVERT() -- -- Date as string SELECT TRY_CONVERT(CHAR(10), GETDATE(), 101) AS RIGHT_DATE -- Time as string SELECT TRY_CONVERT(CHAR(18), GETDATE(), 108) AS RIGHT_TIME -- Try to stuff large number into small space SELECT TRY_CONVERT(TINYINT, POWER(2, 16)) AS TINY_NUMBER |
The output from the TSQL example is shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
output: RIGHT_DATE ---------- 07/24/2013 RIGHT_TIME ------------------ 09:48:32 TINY_NUMBER ----------- NULL |
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.