MySQL STR_TO_DATE NULL on error

I am currently moving a table with dates in columns VARCHARto a new table with columns DATE. I managed to process the string values ​​in the old table in the format "YYYY-MM-DD", but when I try to paste, I got an error message with the date "2006-04-31", because this April had only 30 days ( there was a typo when it was registered)

My question is: how can I set for a NULL column when the date is invalid without receiving an error? My SQL is as follows:

INSERT INTO newFancyTable (created_at)
SELECT str_to_date(created, '%Y-%m-%d') FROM oldCrappyTable;

And the error is as follows:

Error Code: 1292. Incorrect date value: '2006-04-31' for column 'created_at' at row 1

thank

UPDATE

I also tried using the following approach:

INSERT INTO newFancyTable (created_at)
SELECT CAST(created AS DATE) FROM oldCrappyTable;

With the same error, and trying to update oldCrappyTablewill return the same:

UPDATE oldCrappyTable SET created = CAST(created AS DATE);

Both are returning:

Error Code: 1292. Incorrect datetime value: '2006-04-31'

UPDATE 2

, CASE, , 5 , , :

CREATE TABLE dates_temp (
  test_date DATE DEFAULT NULL
) ENGINE=MEMORY;

INSERT INTO dates_temp
SELECT STR_TO_DATE("2006-04-31", '%Y-%m-%d');

DROP TABLE dates_temp;
+3
2

, , , . :

 set @old_sql_mode = @@sql_mode; 
 set sql_mode = ''; 
 -- Run some statements which may result in error
 set sql_mode = @old_sql_mode;

MySQL

+3

@EduardoDennis NULLIF, :

INSERT INTO newFancyTable (created_at)
SELECT nullif(str_to_date(created, '%Y-%m-%d'), from_days(0)) FROM oldCrappyTable;

.

0

Source: https://habr.com/ru/post/1650089/


All Articles