mySQL str_to_date() function returns error

前端 未结 3 446
情书的邮戳
情书的邮戳 2021-01-13 14:30

I keep receiving an error message when trying to convert a column, CreatedDate, of string date values in my Estimates table into the mySQL date format using str_to_date(). M

相关标签:
3条回答
  • 2021-01-13 15:10

    It's hitting blank values in your column.

    SET CreatedDate = str_to_date( '', '%c/%e/%y' )
    

    I think this outputs 0000-00-00 and that works as an invalid date if you are setting a date field to that.

    SET CreatedDate = STR_TO_DATE( IFNULL(case when CreatedDate = '' then null else createddate end,'1901-1-1'), '%c/%e/%y' )
    

    That will leave 1901-01-01 values for nulls and blank

    Added to tadman:

    SET CreatedDate = STR_TO_DATE(case when CreatedDate = '' then null else createddate end, '%c/%e/%y' )
    

    Nulls instead of 1901-01-01 if you prefer.

    0 讨论(0)
  • 2021-01-13 15:13

    Disable NO_ZERO_DATE SQL mode:

    set @old_sql_mode = @@sql_mode; 
    set sql_mode = ''; 
    

    Run your statement:

    UPDATE Estimates
    SET CreatedDate = NULLIF(str_to_date(CreatedDate, '%c/%e/%y'), FROM_DAYS(0))
    

    Then enable original SQL modes:

    set sql_mode = @old_sql_mode;
    

    Disabling NO_ZERO_DATE mode will make STR_TO_DATE return zero date 0000-00-00 for invalid date strings, the same value is returned by FROM_DAYS(0). So NULLIF will convert zero dates to NULL.

    This answer was helpful.

    0 讨论(0)
  • 2021-01-13 15:27

    The usual strategy for cleaning up data like this is as follows:

    ALTER TABLE Estimates CHANGE COLUMN CreatedDate CreatedDateString VARCHAR(255);
    ALTER TABLE Estimates ADD COLUMN CreatedDate DATE
    
    UPDATE Estimates SET CreatedDate=STR_TO_DATE(CreatedDateString, '%c/%e/%y'))
      WHERE CreatedDateString IS NOT NULL AND CreatedDateString != ''
    

    Then when you're confident everything got converted correctly:

    ALTER TABLE Estimates DROP COLUMN CreatedDateString
    

    The advantage to proper DATE fields is they're in a consistent format and when you add an INDEX on them data retrieval is very fast, even on ranges, like:

    SELECT * FROM Estimates WHERE CreatedDate BETWEEN '2016-01-01' AND '2016-06-30'
    
    0 讨论(0)
提交回复
热议问题