MySQL str_to_date没有正确转换日期

时间:2015-09-18 14:47:49

标签: mysql sql

我有以下SQL(使用MySQL 5.6.25社区)为银行信息创建一个新表,然后从CSV文件加载它;但是,当我这样做时,“posting_date”字段设置为NULL:

CREATE TABLE
IF NOT EXISTS account
(id INT PRIMARY KEY AUTO_INCREMENT, 
post_date DATE,
reference_num DECIMAL(24,0),
payee TEXT,
address TEXT,
amount DECIMAL(30,2));

LOAD DATA LOCAL
INFILE '/Users/tkessler/Data/banking.csv'
INTO TABLE account
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
(post_date, reference_num, payee, address, amount)
SET
    post_date = str_to_date(post_date, '%m/%d/%Y'),
    reference_num = cast(substring(reference_num,1,char_length(reference_num)) as DECIMAL(24,0)),
    payee = substring(payee, 2, char_length(payee)-2),
    address = substring(address,2,char_length(address)-2),
    amount = cast(substring(amount,1,char_length(amount)-2) as DECIMAL(30,2));

数据的一些示例行如下:

04/15/2015,24393985105217960500072,"Company 1","Sacramento CA",-68.25
04/14/2015,24493985103247937700049,"Company 2","San Francisco CA",-10.00
04/14/2015,24592165103050851117121,"Company 3","Web Order",-24.99
04/13/2015,24792165102060610562563,"Company 4","Sacramento CA",-3.58
04/13/2015,24826385102370499124382,"Company 5","Sacramento CA",-29.81

当我运行SQL时,我将post_date设置为NULL,但是如果我将post_date数据类型更改为“text”,那么它会显示str_to_date()函数中格式正确的日期字符串(例如,'2015- 04-15'来自这里的第一个示例数据行。)

然后,如果我在str_to_date()函数中使用静态日期字符串(如'01 / 21/2000'而不是'post_date'变量),并且post_date数据类型为'date',那么没有问题,所有导入的条目在post_date字段中获得'2000-01-21'(格式化为所需的日期数据类型)。

我很困惑,因为静态日期字符串转换并正确实现,但即使动态日期变量似乎通过str_to_date()函数转换为格式正确的日期条目,MySQL也无法识别它作为日期,并传递NULL。

我尝试使用substring()函数从正在转换的日期字符串中删除任何可能的不可见前导或尾随字符,但没有任何效果。据我所知,输入日期只是基本文本,格式与静态日期字符串相同,没有任何特殊之处可能导致此问题。

1 个答案:

答案 0 :(得分:1)

如果要对字段进行后处理,则应使用临时变量,如下所示:

LOAD DATA LOCAL
INFILE '/Users/tkessler/Data/banking.csv'
INTO TABLE account
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
(@post_date, reference_num, payee, address, amount)
SET
    post_date = str_to_date(@post_date, '%m/%d/%Y'),