CONVERT Function

The CONVERT function in SQL Server is used to change the data type of an expression. It offers more flexibility than the CAST function by allowing you to specify a style code for date and time conversions.

Syntax

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

Parameters

Return Value

Returns the expression converted to the specified data_type.

Description

The CONVERT function is a powerful tool for data manipulation. It's commonly used for:

Examples

Example 1: Converting a number to a string

Convert an integer to a character string:

SELECT CONVERT(VARCHAR(20), 12345) AS ConvertedString;

Result:

ConvertedString
    --------------------
    12345

Example 2: Converting a string to a date with style

Convert a string in 'YYYY-MM-DD' format to a datetime data type using style 23:

SELECT CONVERT(DATETIME, '2023-10-27', 23) AS ConvertedDate;

Result:

ConvertedDate
    -----------------------
    2023-10-27 00:00:00.000

Example 3: Converting a date to a formatted string

Convert the current date to a string in 'Month Day, Year' format using style 108 (and time):

SELECT CONVERT(VARCHAR(30), GETDATE(), 108) AS FormattedDateTime;

Result (will vary based on current time):

FormattedDateTime
    ------------------------------
    14:30:55.123

Convert the current date to a string in 'YYYY-MM-DD' format using style 23:

SELECT CONVERT(VARCHAR(10), GETDATE(), 23) AS FormattedDate;

Result (will vary based on current date):

FormattedDate
    ----------
    2023-10-27

Example 4: Converting a decimal to an integer

Convert a decimal number to an integer (truncates decimal part):

SELECT CONVERT(INT, 123.789) AS TruncatedInteger;

Result:

TruncatedInteger
    ----------
    123

See Also