Converts an expression of one data type to another data type.
CONVERT ( data_type [ ( length ) ] , expression [ , style ] )
| Parameter | Description |
|---|---|
data_type |
The target data type to which the expression will be converted. This can be any of the system-supplied data types. |
length |
An optional parameter that specifies the length of the target data type. This is only applicable for certain data types like VARCHAR or NVARCHAR. |
expression |
The expression of the source data type that will be converted. This can be a column name, a literal value, or another expression. |
style |
An optional integer value that specifies how the date is converted from one style to another. This is only applicable when converting to or from date and time data types. Common styles include:
|
Returns the converted expression of the specified data_type.
The CONVERT function is a versatile tool in SQL Server for transforming data from one type to another. This is particularly useful for:
SELECT CONVERT(VARCHAR, GETDATE(), 101);
-- Returns the current date in mm/dd/yyyy format, e.g., '10/26/2023'
SELECT CONVERT(VARCHAR(10), 12345.6789);
-- Returns '12345.6789'
SELECT CONVERT(DATETIME, '2023-10-26 14:30:00');
-- Returns a datetime value
SELECT CONVERT(INT, 45.67);
-- Returns 45 (decimal part is truncated)
When converting to string types (VARCHAR, NVARCHAR), be mindful of the specified length parameter. If the converted value exceeds the specified length, it will be truncated, potentially leading to data loss or unexpected results.