Remove all zero dates from MySQL database across all Tables

前端 未结 9 1493
-上瘾入骨i
-上瘾入骨i 2021-01-13 14:37

I have plenty of tables in MySQL which which contains zero date in dateTime column 0000-00-00 00:00:00

Using some sort of admin settings, Is it possibl

相关标签:
9条回答
  • 2021-01-13 14:51

    You can update your table by filtering where dates are equals to 0 and you can define a default value to the column.

    0 讨论(0)
  • 2021-01-13 14:55

    This is an old question but was running into a similar problem except I was trying to set the 0000-00-00 to NULL.

    Was trying to query this

    UPDATE tablename SET date_column = NULL WHERE date_column = '0000-00-00';

    and was getting the following error :

    Incorrect date value: '0000-00-00' for column 'date_column' at row 1

    Turns out the following query without '' around the 0000-00-00 worked !

     UPDATE tablename SET date_column = NULL WHERE date_column = 0000-00-00;
    0 讨论(0)
  • 2021-01-13 14:55

    You have two options.

    Option One - In the programming language of your choice (you can even do this with Stored Procedures):

    1. Loop through your INFORMATION_SCHEMA, probably COLUMNS and build a query to get back the tables you need to affect, i.e.

    -

    SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE COLUMN_NAME='date' AND TABLE_SCHEMA='<YOUR DB NAME>'
    

    or maybe even better

    SELECT TABLE_NAME,COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE COLUMN_NAME in ('timestamp','date','datetime')
    AND TABLE_SCHEMA='<YOUR DB NAME>'
    
    1. Store results and then loop through them. Each loop, create a new query. In MySQL that would be a Stored Procedure with Prepared Statements, AKA:

    -

    @string = CONCAT("UPDATE ", @table_name, " SET ", @column_name, "='1-1-1900' WHERE ", @column_name, "=0000-00-00 00:00:00");
    

    PREPARE stmt FROM @string; EXECUTE stmt;

    That wouldn't be too tough to write up.

    Option Two - Another example, while certainly more low tech, may be no less effective. After doing a mysqldump and before doing your export, you can do a simple search-replace in the file. Vim or any other text editor would do this quite expertly and would allow you to replace 0000-00-00 00:00:00 with 1-1-1900. Because you are almost definitely not going to find situations where you DON'T want that to be replaced, this could be the easiest option for you. Just throwing it out there!

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