Home > Database > Mysql Tutorial > body text

Usage of mysql cast and convert functions

伊谢尔伦
Release: 2016-11-24 16:03:27
Original
1414 people have browsed it

MySQL's CAST() and CONVERT() functions can be used to obtain a value of one type and produce a value of another type. The specific syntax of the two is as follows:

CAST(value as type);
CONVERT(value, type);
Copy after login

is CAST (xxx AS type), CONVERT (xxx, type).

The types that can be converted are limited. This type can be one of the following values:

Binary, with the effect of binary prefix: BINARY

Character type, can take parameters: CHAR()

Date: DATE

Time: TIME

Date time type: DATETIME

Floating point: DECIMAL

Integer: SIGNED

Unsigned integer: UNSIGNED Here are a few examples:

Example 1

mysql> SELECT CONVERT('23',SIGNED);
+----------------------+
| CONVERT('23',SIGNED) |
+----------------------+
|         23 |
+----------------------+
1 row in set
Copy after login

Example 2

mysql> SELECT CAST('125e342.83' AS signed);
+------------------------------+
| CAST('125e342.83' AS signed) |
+------------------------------+
|             125 |
+------------------------------+
1 row in set
Copy after login

Example 3

mysql> SELECT CAST('3.35' AS signed);
+------------------------+
| CAST('3.35' AS signed) |
+------------------------+
|           3 |
+------------------------+
1 row in set
Copy after login

Like the above example, change To convert varchar to int, use cast(a as signed), where a is a string of type varchar.

Example 4

In SQL Server, the following code demonstrates the hexadecimal storage result of date storage when the datetime variable contains only a simple date and a simple time.

DECLARE @dt datetime
  
--单纯的日期
SET @dt='1900-1-2'
SELECT CAST(@dt as binary(8))
--结果: 0x0000000100000000
  
--单纯的时间
SET @dt='00:00:01'
SELECT CAST(@dt as binary(8))
--结果: 0x000000000000012C
Copy after login

MySQL's type conversion is the same as that of SQL Server, but the type parameters are a little different: CAST(xxx AS type), CONVERT(xxx, type).

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template