Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting MySQL warning into an error

Is there any way to convert the warning that MySQL is issuing about an invalid datetime into a hard error? I've tried using SET sql_mode='TRADITIONAL'; which apparently is supposed to turn (some) things that are warnings into errors, but it does not have any effect here. This is MySQL 5.1.56. Something that works on a session-level would be ideal, but I'll take what I can get.

mysql> describe test_table2;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| value    | int(11)     | YES  |     | NULL    |       |
| name     | varchar(16) | YES  |     | NULL    |       |
| sometime | datetime    | YES  |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> select * from test_table2;
+-------+-------+---------------------+
| value | name  | sometime            |
+-------+-------+---------------------+
|     1 | one   | 2002-09-01 10:00:00 |
|     2 | two   | 2002-09-02 11:00:00 |
|     3 | three | 2002-09-03 12:00:00 |
|     4 | four  | 2002-01-04 13:00:00 |
|     5 | five  | 2002-01-05 14:00:00 |
+-------+-------+---------------------+
5 rows in set (0.00 sec)

mysql> select * from test_table2 where sometime = 'foo';
Empty set, 2 warnings (0.00 sec)

Warning (Code 1292): Incorrect datetime value: 'foo' for column 'sometime' at row 1
Warning (Code 1292): Incorrect datetime value: 'foo' for column 'sometime' at row 1
like image 821
Jack Lloyd Avatar asked Jul 27 '26 19:07

Jack Lloyd


1 Answers

With SET sql_mode='TRADITIONAL', doing an INSERT with an invalid date causes an error, but doing a SELECT with an invalid date still causes a warning. You can trigger the error by passing the (possibly invalid) date value to this query first:

CREATE TEMPORARY TABLE IF NOT EXISTS date_guard (date DATE) SELECT 'foo' AS date;

where 'foo' is the date value you want to validate.

like image 151
gcbenison Avatar answered Jul 30 '26 09:07

gcbenison