TRY_CONVERT
Description
Returns a value cast to the specified data type if the cast succeeds; otherwise, returns null.
Syntax
TRY_CONVERT ( data_type [ ( length ) ], expression [, style ] ) Source Patterns
Basic Transformation
In order to transform this function, we have to check the parameters of the TRY_CONVERT first.
TRY_CONVERT( INT, 'test')If the expression that needs to be casted is a string, it will be transfomed to TRY_CAST, which is a function of Snowflake.
TRY_CAST( 'test' AS INT)TRY_CAST
The TRY_CAST shares the same transformation with TRY_CONVERT.
Example
Sql Server
The result will be the same with the example of TRY_CONVERT.
Snowflake
Known Issues
If the data type is Varchar or Char, then it will be transformed differently.
If TRY_CAST is used with VARCHAR or CHAR in Snowflake, it will cause an error, so it will be transformed to
The same happens with the data types of SQL_VARIANT and GEOGRAPHY.
Are transformed to
If the expression is not a string, there is a very high chance that it will fail, since the TRY_CAST of snowflake works only with string expressions.
In this case, another transformation will be done
Will be transformed to
Now, with these transformation, there could be problems depending on what is being done with the functions. The TRY_CONVERT of SqlServer returns nulls if the convertion was not possible.
This can be used to do logic like this
That type of conditions with the TRY_CONVERT can be used with the TRY_CAST, but what happens if it is transformed to TO_VARCHAR, TOCHAR or to the CAST? If the convertion in those functions fails, it will cause an error instead of just returning null.
Examples
In this sample we have several TRY_CONVERT with different data types
Sql Server
If we migrate that select, we will get the following result
Snowflake
Let's execute each one and compare the result.
NUMERIC_RESULT
12345
12345
DECIMAL_RESULT
123.45
123.45
INT_RESULT
123
123
FLOAT_RESULT
123.02
123.02
DOUBLE_PRECISION_RESULT
123.02
123.02
DATE_RESULT
2017-01-01
2017-01-01
DATETIME_RESULT
2017-01-01 12:00:00.000
2017-01-01 12:00:00.000
SMALLDATETIME_RESULT
2017-01-01 12:00:00
2017-01-01 12:00:00.000
TIME_RESULT
12:00:00.0000000
12:00:00
TIMESTAMP_RESULT
0x323031372D30312D
2017-01-01 12:00:00.000
DATETIMEOFFSET_RESULT
2017-01-01 12:00:00.0000000 +00:00
2017-01-01 12:00:00.000 -0800
VARCHAR_RESULT
1234
1234
CHAR_RESULT
1
1
SQL_VARIANT_RESULT
2017-01-01 12:00:00
"2017-01-01 12:00:00"
GEOGRAPHY_RESULT
0xE610000001148716D9CEF7D34740D7A3703D0A975EC08716D9CEF7D34740CBA145B6F3955EC0
{ "coordinates": [ [ -122.36, 47.656 ], [ -122.343, 47.656 ] ], "type": "LineString" }
Last updated