mysql alter date,无法在MySql中将varchar转换为datetime

In my MySql table there's a column called _time of type varchar. The values it holds are in the format: year month day hour minute without the whitespaces: 201409201945 I want to convert it to datetime so I'm doing this:

ALTER TABLE `my_table` CHANGE COLUMN `_time` `date_time` DATETIME NOT NULL;

And it throws this error for some reason:

Error Code: 1292. Incorrect datetime value: '201409201945' for column '_date_time' at row 1 0.036 sec

解决方案

The three steps @Arkain mentioned would be with the help of the function STR_TO_DATE

-- add the new column

ALTER TABLE `my_table` ADD COLUMN `date_time` DATETIME;

-- update the new column with the help of the function STR_TO_DATE

UPDATE `my_table` SET `date_time` = STR_TO_DATE(`_time`, '%Y%m%d%H%i');

-- drop the old column

ALTER TABLE `my_table` DROP COLUMN `_time`;

The complete list of specifiers for STR_TO_DATE can be found at DATE_FORMAT, here an excerpt with those I used:

%d Day of the month, numeric (00..31)

%H Hour (00..23)

%i Minutes, numeric (00..59)

%m Month, numeric (00..12)

%Y Year, numeric, four digits

If the new column should have the attribute NOT NOLL, one way could be to set the sql mode before the operation to '' and reset the sql_mode later on:

SET @old_mode = @@sql_mode;

SET @@sql_mode = ''; -- permits zero values in DATETIME columns

ALTER TABLE `my_table` ADD COLUMN `date_time` DATETIME NOT NULL;

UPDATE `my_table` SET `date_time` = STR_TO_DATE(`_time`, '%Y%m%d%H%i');

ALTER TABLE `my_table` DROP COLUMN `_time`;

SET @@sql_mode = @old_mode;

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值