TRY_CONVERT(): TRY_CONVERT is somewhat same as we have TryParse in C#; it takes the value passed to it and tries to convert it to the specified data type. If the cast succeeds, TRY_CONVERT returns the value as the specified data type; if an error occurs, null is returned.
For example:
SET DATEFORMAT dmy;
SELECT TRY_CONVERT(datetime2, '11/19/2010') AS Result;
GO
|
And result will be Null, as it considers 19 as month, now try as follows:
SET DATEFORMAT mdy;
SELECT TRY_CONVERT(datetime2, '11/19/2010') AS Result;
GO
|
Result:
2010-11-19 00:00:00.0000000
|
However if you request a conversion that is explicitly not permitted, then TRY_CONVERT fails with an error.
The following example demonstrates that TRY_CONVERT returns an error when the cast is explicitly not permitted.
SELECT TRY_CONVERT(xml, 4) AS Result;
GO
|
This conversion throw error as: Explicit conversion from data type int to xml is not allowed.
Comments
Post a Comment