南大通用GBase 8a从字符串转数字类型的几种方法

GBase 8a数据库集群,可以通过cast, to_number等函数从字符串转成数字,本文介绍各个函数的写法和样例。

参考

相似功能

GBase 8a从字符串转数字的函数to_number介绍和样例

反向功能

GBase 8a将数字转字符串to_char函数功能介绍和样例

相关功能

GBase 8a的强制类型转换cast和convert的用法例子

隐式转换

绝大部分字符串,如果符合数字的格式,是可以自动转成数字的,不需要显示转换。

gbase> select '123'/10;
+----------+
| '123'/10 |
+----------+
|     12.3 |
+----------+
1 row in set (Elapsed: 00:00:00.03)

to_number强制转换

详情请参考 to_number函数的使用文档。GBase 8a从字符串转数字的函数to_number介绍和样例

如下例子增加to_number函数后,会自动将数据类型从字符串转成数字。

gbase> create table a1 as select to_number('123.45') num from dual;
Query OK, 1 row affected (Elapsed: 00:00:00.37)

gbase> desc a1;
+-------+--------+------+-----+---------+-------+
| Field | Type   | Null | Key | Default | Extra |
+-------+--------+------+-----+---------+-------+
| num   | double | NO   |     | NULL    |       |
+-------+--------+------+-----+---------+-------+
1 row in set (Elapsed: 00:00:00.00)

gbase> create table a2 as select '123.45' num from dual;
Query OK, 1 row affected (Elapsed: 00:00:00.36)

gbase> desc a2;
+-------+------------+------+-----+---------+-------+
| Field | Type       | Null | Key | Default | Extra |
+-------+------------+------+-----+---------+-------+
| num   | varchar(6) | YES  |     |         |       |
+-------+------------+------+-----+---------+-------+
1 row in set (Elapsed: 00:00:00.00)

cast / convert函数

该函数的详情请参考 GBase 8a的强制类型转换cast和convert的用法例子

如下例子是将其它类型,包括字符串,强制转化为数字的方法,包括int整数和decimal的浮点数。

gbase> select cast('123.45' as int);
+-----------------------+
| cast('123.45' as int) |
+-----------------------+
|                   123 |
+-----------------------+
1 row in set, 1 warning (Elapsed: 00:00:00.00)

gbase>
gbase>
gbase> select cast('123.45' as decimal(10,3));
+---------------------------------+
| cast('123.45' as decimal(10,3)) |
+---------------------------------+
|                         123.450 |
+---------------------------------+
1 row in set (Elapsed: 00:00:00.00)