首页 > 解决方案 > SELECT 和 INSERT 语句中 str_to_date 的不同行为

问题描述

我有与这个问题相同的问题 - MySQL Unable to insert WHERE STR_TO_DATE IS NULL

我想将日期从一个数据库迁移到另一个数据库。原始数据库中的日期存储为 varchars,并不总是有效 - 例如,有时有一个像“nb”或其他字符串这样的值,有时它们是空的。在 SELECT 语句中使用 str_to_date() 可以正常工作 - 如果提供的字符串与提供的格式不匹配,则返回 null。这是我想要的行为,但在 INSERT 语句中。不幸的是,在尝试这样做时,我收到以下错误:

SQL Error (1411): Incorrect datetime value: 'n.b.' for function str_to_date

你有什么建议可以避免这种行为吗?

如果这很重要,我正在使用 MariaDB。

编辑 1:这是我的 INSERT 语句:

insert into person
(id, firstname, lastname, date_of_birth, place_of_birth, gender, old_id)
select
vm.person_id, 
 IFNULL(wv.vorname, '') as firstname, 
 IFNULL(wv.NAME, '') as lastname, 
STR_TO_DATE(wv.geburtsdatum, '%e.%c.%Y') as date_of_birth, 
null as place_of_birth, 
case
    when wv.anrede = 'Herr' then 'm'
    when wv.anrede = 'Frau' then 'w'
    else 'x'
end as gender, 
 vm.old_id
from b.helper_table vm
join a.orig_table wv
on vm.old_id = wv.id;

标签: mysqlsqlsql-insertstr-to-date

解决方案


它适用于正则表达式 - 感谢@MatBailie。

insert into person
(id, firstname, lastname, date_of_birth, place_of_birth, gender, old_id)
select
vm.person_id, 
IFNULL(wv.vorname, '') as firstname, 
IFNULL(wv.name, '') as lastname, 
case
    when wv.geburtsdatum REGEXP '^[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{4}$' then 
    str_to_date(wv.geburtsdatum, '%e.%c.%Y')
end as date_of_birth, 
null as place_of_birth, 
case 
    when wv.anrede = 'Herr' then 'm'
    when wv.anrede = 'Frau' then 'w'
    else 'x'
end as gender, 
 vm.old_id
from b.helper_table vm
join a.orig_table wv
on vm.old_id = wv.id;

推荐阅读