如何在 MySQL 中将列从 varchar 转换为 decimal,知道这些值是用逗号分隔的
How to convert a column from varchar to decimal in MySQL, knowing that the values are separated with commas
我尝试了以下 MySQL 将列从 varchar 类型转换为 decimal 类型的请求,但出现错误。
ALTER TABLE `cmd-services` CHANGE `Qte Sortie` `Qte Sortie` CAST(REPLACE(`Qte Sortie`, ',', '.') as DECIMAL(20,2));
ALTER TABLE `cmd-services` MODIFY `Qte Sortie` CAST(REPLACE(`Qte Sortie`, ',', '.') as DECIMAL(20,2));
我需要你的帮助。
谢谢
分两步完成
- 更新列并将所有非数字值设置为空,以便更改
不会失败的。
- 改变 table 并将类型设置为 int
第 1 步:
UPDATE `cmd-services`
set `Qte Sortie` = CAST(REPLACE(`Qte Sortie`, ',', '.') as DECIMAL(20,2));
第 2 步:
ALTER TABLE `cmd-services`
MODIFY `Qte Sortie` DECIMAL(20,2);
This takes the assumption that the columns allow nulls. If not then
that needs to be handled as well.
For example: By altering the column to allow null, then after it has
been converted to DECIMAL then set all null values to 0 and alter the
table to not allow null.
我尝试了以下 MySQL 将列从 varchar 类型转换为 decimal 类型的请求,但出现错误。
ALTER TABLE `cmd-services` CHANGE `Qte Sortie` `Qte Sortie` CAST(REPLACE(`Qte Sortie`, ',', '.') as DECIMAL(20,2));
ALTER TABLE `cmd-services` MODIFY `Qte Sortie` CAST(REPLACE(`Qte Sortie`, ',', '.') as DECIMAL(20,2));
我需要你的帮助。 谢谢
分两步完成
- 更新列并将所有非数字值设置为空,以便更改 不会失败的。
- 改变 table 并将类型设置为 int
第 1 步:
UPDATE `cmd-services`
set `Qte Sortie` = CAST(REPLACE(`Qte Sortie`, ',', '.') as DECIMAL(20,2));
第 2 步:
ALTER TABLE `cmd-services`
MODIFY `Qte Sortie` DECIMAL(20,2);
This takes the assumption that the columns allow nulls. If not then that needs to be handled as well.
For example: By altering the column to allow null, then after it has been converted to DECIMAL then set all null values to 0 and alter the table to not allow null.