Scalar Conversion Functions

Conversion functions transform an expression from one data type to another. They are essential for ensuring data compatibility and for formatting output.

Supported Functions

FunctionPurposeSyntax
CAST Convert an expression to a specified data type. CAST ( expression AS data_type [ ( length ) ] )
CONVERT Similar to CAST but supports style codes for date/time and binary conversions. CONVERT ( data_type [ ( length ) ], expression [, style ] )
TRY_CAST Returns NULL when conversion fails instead of raising an error. TRY_CAST ( expression AS data_type [ ( length ) ] )
TRY_CONVERT Same as TRY_CAST with style support. TRY_CONVERT ( data_type [ ( length ) ], expression [, style ] )
PARSE Parse a string to a date/time or numeric value using culture information. PARSE ( string_value AS data_type [ USING culture ] )
TRY_PARSE Returns NULL on parsing failure. TRY_PARSE ( string_value AS data_type [ USING culture ] )

Style Codes for CONVERT

When converting dates or binary data, specify a style code to control the output format.

SELECT CONVERT(varchar, GETDATE(), 101)   -- 06/25/2025
SELECT CONVERT(varchar, GETDATE(), 112)   -- 20250625
SELECT CONVERT(varbinary, 'ABC', 2)       -- 0x414243

Examples

Basic CAST

SELECT CAST('123' AS int) AS IntegerValue;
-- Result: 123

CONVERT with style

SELECT CONVERT(varchar(10), OrderDate, 101) AS USFormatDate
FROM Orders;
-- Returns dates as MM/DD/YYYY

TRY_CAST handling bad data

SELECT TRY_CAST('ABC' AS int) AS Result;   -- Result: NULL

PARSE using culture

SELECT PARSE('12,5' AS decimal(10,2) USING 'fr-FR') AS FrenchDecimal;
-- Result: 12.5

Related Topics