How to set to NULL a datetime with 0000-00-00 00:00:00 value?

后端 未结 5 1670
夕颜
夕颜 2021-02-08 18:37

I need to change a few values on my DB.

I forgot to set nullable to the table and it set to 0000-00-00 00:00:00 by default.

Now I need to convert that value in <

相关标签:
5条回答
  • 2021-02-08 19:13

    You need to first make the column nullable:

    ALTER TABLE mytable MODIFY COLUMN field DATETIME NULL;
    

    And then update the values:

    UPDATE mytable SET field = NULL WHERE field = '0000-00-00 00:00:00';
    
    0 讨论(0)
  • 2021-02-08 19:16

    Unfortunately this will not work.
    for:

    update episodes set `ending` = NULL 
    WHERE `ending` = '0000-00-00'
    

    If 0000-00-00 is in the where clause, you get the error:

    "1292 - Incorrect datetime value: '0000-00-00' for column 'ending' at row 1".

    even if ending has NULL and defalut=null in field definition.

    0 讨论(0)
  • 2021-02-08 19:22

    You need to first make the column nullable:

    @Mysql5.7

    Wrong :

    update episodes set `ending` = NULL WHERE `ending` = '0000-00-00'
    

    Correct :

    update episodes set `ending` = NULL WHERE `ending` = 0000-00-00
    

    Note: Remove the quote from the date value in your where clause. Hope it help someone

    0 讨论(0)
  • 2021-02-08 19:27

    What worked for me is:

    1. Set the field from datetime to varchar(191).
    2. Update all rows with field = '0000-00-00 00:00:00' to NULL.
    3. Set the field back to datetime.
    0 讨论(0)
  • 2021-02-08 19:36

    From MySQL 5.7, SQL mode NO_ZERO_DATE makes this update impossible unless you firstly disable this restriction (for the duration of the transaction only).

    SET sql_mode=(SELECT REPLACE(@@sql_mode,"NO_ZERO_DATE", ""));
    UPDATE mytable SET field = NULL WHERE field = '0000-00-00 00:00:00';
    
    0 讨论(0)
提交回复
热议问题