Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Incorrect datetime value error – MYSQL dynamic query

I tried the following query in MYSQL and I am getting Incorrect datetime value error. How to solve this error?

create table Test(id datetime, title varchar(100));
insert into Test(id, title) values('2017-01-11', "Hello");
insert into Test(id, title) values('2018-01-11', "Hello");
SET @trimRetaineddate = '2017-01-11';
SET @delete_text = CONCAT('DELETE FROM Test WHERE id = ', CONVERT(@trimRetaineddate,DATE));
PREPARE delete_stmt FROM @delete_text;
EXECUTE delete_stmt;
select * from Test;

The error I got:
Incorrect datetime value: ‘2005’ for column ‘id’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Date literals in MySQL should be surrounded by single quotes:

SET @trimRetaineddate = '2017-01-11';
SET @delete_text = CONCAT('DELETE FROM Test WHERE id = ''', @trimRetaineddate, '''');
SELECT @delete_text;  -- DELETE FROM Test WHERE id = '2017-01-11'
PREPARE delete_stmt FROM @delete_text;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading