从 VARCHAR 转换为 INT - MySQL

2021-11-20 00:00:00 sql mysql

我的当前数据

SELECT PROD_CODE FROM `PRODUCT`

PROD_CODE
2
5
7
8
22
10
9
11

我已经尝试了所有四个查询,但都没有奏效.(参考)

I have tried all the four queries and none work. (Ref)

SELECT CAST(PROD_CODE) AS INT FROM PRODUCT;

SELECT CAST(PROD_CODE AS INT) FROM PRODUCT;

SELECT CAST(PROD_CODE) AS INTEGER FROM PRODUCT;

SELECT CAST(PROD_CODE AS INTEGER) FROM PRODUCT;

所有抛出语法错误如下:

All throw syntax errors such as below:

您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册以了解要使用的正确语法靠近 ') AS INT FROM PRODUCT LIMIT 0, 30' 在第 1 行

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') AS INT FROM PRODUCT LIMIT 0, 30' at line 1

您的 SQL 语法有错误;检查手册对应于您的 MySQL 服务器版本以使用正确的语法在第 1 行距离 PRODUCT LIMIT 0, 30' 附近的 'INTEGER)

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INTEGER) FROM PRODUCT LIMIT 0, 30' at line 1

在 MySQL 中将 varchar 转换为整数的正确语法是什么?

What is the right syntax to cast varchar to integer in MySQL?

MySQL 版本:5.5.16

MySQL Version: 5.5.16

推荐答案

如Cast 函数和运算符:

结果的类型可以是以下值之一:

The type for the result can be one of the following values:

  • BINARY[(N)]
  • CHAR[(N)]
  • 日期
  • 日期时间
  • 十进制[(M[,D])]
  • SIGNED [INTEGER]
  • TIME
  • UNSIGNED [INTEGER]

因此,您应该使用:

SELECT CAST(PROD_CODE AS UNSIGNED) FROM PRODUCT

相关文章