简体   繁体   中英

VARCHAR to DATE - MySQL

I'm kinda new at database world and got stucked in my work with the every column in the database that supposed to be DATETIME, or TIMESTAMP, or anything related to date is VARCHAR(250) Ex.: 201610251557.

My question is, there is a way, to change the column to date, withou losing the values on it?

I already tried to change the column structure, but it changes every value to 0000-00-00 00-00.

You can have a look at str_to_date; it operates like this:

SELECT STR_TO_DATE('201610251557', '%Y%m%d%H%i');

With that iso formatted output, perhaps you can update your column like this:

update my_table set datecol = STR_TO_DATE(datecol, '%Y%m%d%H%i');

Safest scenario is:

  1. add a new field with the correct type
  2. update data until new field is populated with appropriate data for all rows
  3. (optional) delete (or rename for archival purposes) old field
  4. (optional) rename new field to original field's name

您可以使用str_to_date()函数创建另一个表,然后将以前的重命名新表删除为先前的表,或将其恢复为原始表。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM