Share via


How to use TRY_CAST for Windows Azure SQL Database

How To

TRY_CONVERT conversion function is supported in SQL Server 2012, but it is not supported in Windows Azure SQL Database, so we have to use TRY_CAST in Windows Azure SQL Database. TRY_CAST returns the value as the specified data_type; if an error occurs, null is returned.

However if you request a conversion that is explicitly not permitted, then TRY_CAST fails with an error. In Windows Azure SQL Database so you have to use TRY_CAST in place of TRY_CONVERT. TRY_CAST is same as  TRY_CONVERT, as CAST is analogous to CONVERT, but CONVERT's expression and style arguments are different.

T-SQL Example

TRY_CAST will be used as following example shows,

SELECT
    CASE WHEN TRY_CAST('xyz' AS float) IS NULL
  THEN 'Cast has failed'
    ELSE 'Cast has succeeded'
END AS Result;
GO

TRY_CONVERT performs same functionality in SQL Server 2012. Currently Windows Azure SQL Database does not support TRY_CONVERT.

SELECT     CASE WHEN TRY_CONVERT(float, 'xyz') IS NULL     THEN 'Cast has failed'     ELSE 'Cast has succeeded' END AS Result; GO

References

TRY_CAST example can be downloaded from following link

http://gallery.technet.microsoft.com/TRYCAST-example-for-3b59e3ae