Friday, March 31, 2017

TRY_CAST vs TRY_CONVERT vs TRY_PARSE


TRY_CAST
Syntax : TRY_CAST (expression AS data_type)

expression is the value you want to convert.
data_type is the new type you want to convert your value to.

If the conversion succeeds, TRY_CAST returns value in the new type; otherwise it returns null.
TRY_CAST is not a new reserved keyword and It is available in all levels.
It is available in SQL Server 2012 and later versions.
TRY_CAST will fail with an error if the conversion is not possible!

Examples:

TRY_CONVERT
Syntax : TRY_CONVERT (data_type, expression, [style])

data_type is the new type you want to convert your value to.
expression is the value you want to convert.
style is an integer expression specifies how the conversion should translate the expression.

If the conversion succeeds, TRY_CONVERT returns the value in new type; otherwise it returns null.
It is available in SQL Server 2012 and later versions.
TRY_CONVERT is not supported on SQL Azure.
It is a reserved keyword and It needs level 100 and higher.

Examples:

TRY_PARSE
Syntax : TRY_PARSE (string_value AS data_type [USING culture])

string_value : nvarchar(4000) value
data_type : Data Type to convert.
culture: culture of the data_type (Optional)

TRY_PARSE should be use only for converting from string to date/time and number types. It relies on .NET Framework CLR, It will not be remoted and it would cause error on the remote server since it depends on the CLR.

1 comment: