Data Type Conversion
In SQL statements, data type conversion is a common operation. This article will introduce how to perform data type conversion in SQL, as well as related functions and syntax.
Data Type Conversion Functions
CAST Function
The CAST function is used to convert a value of one data type to another data type. If the conversion exceeds the range of the target data type, an overflow exception will be raised.
Syntax
Parameter Description:
- expression: Required. The data source to be converted.
- type: Required. The target data type. Usage is as follows:
CAST(double AS bigint)
: Converts a DOUBLE data type value to a BIGINT data type.CAST(string AS bigint)
: Converts a string to a BIGINT data type. If the string contains a number expressed as an integer, it is directly converted to the BIGINT type. If the string contains a number expressed as a floating point or exponential form, it is first converted to the DOUBLE data type, and then to the BIGINT data type.CAST(string AS timestamp)
orCAST(timestamp AS string)
: Uses the default date formatyyyy-MM-dd HH:mm:ss
.
Example
TRY_CAST Function
The TRY_CAST function is used to convert a value from one data type to another. If the conversion is successful, it returns the converted value; if the conversion fails, it returns NULL.
Syntax
Parameter Description:
- expression: Required. The expression to be converted.
- type: Required. The target data type.
Example
Conversion Operators
In addition to using functions for data type conversion, you can also use conversion operators.
Syntax
- expression: Required. The expression to be converted.
- type: Required. The target data type.