获取MySQL中的变量类型

问题描述 投票:12回答:3

如果我定义一个像set @a = "1";这样的变量。我怎么能看到@a是一个字符串?

sql mysql
3个回答
4
投票

您无法确定MySQL中变量的类型。

作为替代方案,您可以轻松地按照您想要的类型CAST()变量:

@a = CAST(123 AS CHAR);

有关在MySQL手册中进行转换的更多信息和示例:

11.9. Cast Functions and Operators


14
投票

您可以确定MySQL中变量的类型。通过选择变量创建表,然后检查列类型:

set @a:="1"; -- your variable

drop temporary table if exists foo;
create temporary table foo select @a; -- dirty magic
desc foo;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| @a    | longtext | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+

1
投票

在MySql中,您无法识别变量的数据类型。但是有一种方法可以通过使用cast来识别字符串和整数:

set @a = "11";
SELECT CAST(@a AS SIGNED); // Output : 11

set @a = "text";
SELECT CAST(@a AS SIGNED); // Output : 0


set @a = "121212";
SELECT CAST(@a AS SIGNED); // Output : 121212

set @a = "Mysql is open source";
SELECT CAST(@a AS SIGNED); // Output : 0
© www.soinside.com 2019 - 2024. All rights reserved.