Convert varchar column to date in mysql at database level

后端 未结 3 1864
难免孤独
难免孤独 2020-12-11 01:05

I have one column date1 which is varchar type I want this column to date type. I tried changing field but all date is converted to 0

相关标签:
3条回答
  • 2020-12-11 01:29
    UPDATE `table`
    SET `column` = str_to_date( `column`, '%d-%m-%Y' );
    

    More about STR_TO_DATE function.


    Since your column name is date1, you can replace column with date1 in the above syntax, and the code shall be:

    UPDATE `table`
    SET `date1` = str_to_date( `date1`, '%d-%m-%Y' );
    
    0 讨论(0)
  • 2020-12-11 01:49

    The other answers here are risky, because if they go wrong you'll lose your data. A safer way to do this is to create a new field on your database with a DATE (or DATETIME if you need time as well) format, then to run a query like

    UPDATE `table` SET `my_new_date_field` = STR_TO_DATE( `my_old_data_field`, '%d/%m/%Y');
    

    In this way, if the %d/%m/%Y bit is wrong, you won't lose your data.

    Once you're happy, you can delete the old data field and rename the new one.

    0 讨论(0)
  • 2020-12-11 01:55

    use STR_TO_DATE Function of MySQL

    FIRST you will need to update the value in date format.

    UPDATE `tbl` SET `date1` = STR_TO_DATE(`date1`, '%d-%m-%Y') WHERE 1=1
    

    THEN Convert the field to date.

    Most importantly remember to insert date as Y-m-d format, after then.

    0 讨论(0)
提交回复
热议问题