TRY_CONVERT

TRY_CONVERT#

Converts a value to a specified data type, like CONVERT, but returns NULL instead of an error when the value cannot be converted or the style does not apply to it.

Syntax#

TRY_CONVERT ( data_type [ ( length ) ], expression [ , style ] )

Return type#

data_type, always nullable. A varchar or nvarchar without a length is 30 characters long.

Examples#

SELECT TRY_CONVERT(date, '31/12/2024', 103);   -- 2024-12-31
SELECT TRY_CONVERT(date, '31/13/2024', 103);   -- NULL: there is no month 13
SELECT TRY_CONVERT(datetime, '2024-01-01', 999); -- NULL: an unknown style
SELECT TRY_CONVERT(varbinary(10), '1F', 2);    -- 0x1F
SELECT TRY_CONVERT(int, '12', NULL);           -- NULL: a NULL style

Remarks#

TRY_CONVERT follows the rules of TRY_CAST: only the conversion of the value returns NULL, and an error raised while computing the value, or a conversion between two data types that is not allowed at all (error 529), still raises. A style that is unknown or does not apply to the conversion returns NULL where CONVERT raises an error.

A NULL style makes TRY_CONVERT return NULL, as described for CONVERT; conversions from xml or geometry, and to xml, sql_variant or geometry, ignore the style.

TRY_CONVERT is a reserved keyword, as in SQL Server: to use it as a column name or an alias, delimit it, for example [TRY_CONVERT].

Note

The style is an integer expression, as for CONVERT: a style of another type is refused even by TRY_CONVERT. On a SQL Server data source Querona sends TRY_CONVERT to the source, except a conversion whose answer depends on the session’s DATEFORMAT or LANGUAGE: character text read as a date or time with any style, a date or time written as text without a style or with a style that writes month names, and a sql_variant converted to text or a date or time. On other data sources Querona evaluates TRY_CONVERT itself. Where Querona evaluates it, a style that reads a column is refused with an error, as for CONVERT. Before this release, TRY_CONVERT ran as CONVERT and raised an error for a value it could not convert.

A date read with a style follows SQL Server: TRY_CONVERT(date, '12/31/2024', 103) returns NULL, and a style the target type does not read, such as TRY_CONVERT(date, '2024-05-06', 26), returns NULL too. See Date and time.

See Also#