SQL CONVERT Function Example
SQL CONVERT is an inbuilt function that is used for converting an expression from one data type to another data type. Here, if the conversion takes place, then a value with specified conversion will be returned. Otherwise, the function will return an error.
SQL CONVERT() function converts the value (of any type) into a specified datatype.
CONVERT ( target_type [ ( length ) ] , expression [ , style ] )
- Target_type: The data type to which the expression will be converted.
- Length: It is entirely optional. It signifies the length of the resulting data type for expression. It defaults up to 30.
- Expression: The value to be converted to another datatype.
- Style: It is an optional integer that determines the format of the converted expression.
- The result is truncated when the expression is converted to integer datatype when converted from float or integer.
- For other conversions, the value is rounded.
SELECT CONVERT (INT, 10.85);
As the expression is converted from float to integer. So, the result here is truncated.
SELECT CONVERT (float, 10.85);
As the expression is converted to float datatype. So, the result here is not truncated, and the original expression was returned, which was already in the float.
SELECT CONVERT (varchar, 15.6);
Here, the floating expression was converted to character datatype.
SELECT CONVERT (float, ‘15.6’);
Here, the character data type is converted to a floating-point value.
SELECT CONVERT (datetime, '2020-02-26');
Here, the string expression is converted to datetime expression.
SELECT CONVERT (varchar, '02/26/2020', 101);
The Convert() function converted the current date to varchar datatype with the specified style.