Microsoft Learn

CONVERT (SQL Server)

Converts an expression from one data type to another. This is useful for coercing a value into a specific format, such as date or numeric representation.

Syntax

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

Parameters

data_type

The target data type to which the expression will be converted.

length

(Optional) For character or binary data types, this specifies the length of the target data type.

expression

The expression to be converted.

style

(Optional) An integer value that specifies how the date or number is formatted. The interpretation of the style parameter depends on the target data_type.

Return Value

Returns the converted value of the specified data_type.

Examples

Example 1: Converting a date to a different format

SELECT CONVERT(varchar, GETDATE(), 101); -- Returns MM/DD/YYYY format
SELECT CONVERT(varchar, GETDATE(), 103); -- Returns DD/MM/YYYY format

Example 2: Converting a numeric value to a string

SELECT CONVERT(varchar, 123.45); -- Returns '123.45'

Example 3: Converting a string to a numeric type

SELECT CONVERT(int, '1234'); -- Returns 1234
SELECT CONVERT(decimal(10,2), '99.50'); -- Returns 99.50

Example 4: Converting a date to a different date type

SELECT CONVERT(datetime, '2023-10-27 10:30:00'); -- Returns a datetime value

Remarks

Note

The CAST function is an ANSI standard function that provides similar functionality to CONVERT. In many cases, CAST is preferred for its readability and adherence to standards.

See Also