不正确的日期时间值错误 - MYSQL 动态查询
Incorrect datetime value error - MYSQL dynamic query
我在 MYSQL 中尝试了以下查询,但出现了不正确的日期时间值错误。如何解决这个错误?
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;
我得到的错误:
日期时间值不正确:列 'id'
为“2005”
MySQL 中的日期文字应该用单引号括起来:
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;
根据你的拼写
@delete_text 的结果是
从测试中删除 ID = 2017-01-11
MySQL数据库最后执行的SQL是DELETE FROM Test WHERE id = 2005 (2017-1-11=2005)
因为缺少引号
改成这样就可以执行了
SET @delete_text = CONCAT('DELETE FROM Test WHERE id = ','''' ,CONVERT(@trimRetaineddate,DATE),'''');
我在 MYSQL 中尝试了以下查询,但出现了不正确的日期时间值错误。如何解决这个错误?
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;
我得到的错误: 日期时间值不正确:列 'id'
为“2005”MySQL 中的日期文字应该用单引号括起来:
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;
根据你的拼写 @delete_text 的结果是 从测试中删除 ID = 2017-01-11
MySQL数据库最后执行的SQL是DELETE FROM Test WHERE id = 2005 (2017-1-11=2005)
因为缺少引号
改成这样就可以执行了 SET @delete_text = CONCAT('DELETE FROM Test WHERE id = ','''' ,CONVERT(@trimRetaineddate,DATE),'''');