Reputation: 982
Hi I am have the following CSV format
id (tab) creation_date
-------------------------
1 2012-05-04 15:26:45.000
2 NULL
For the importing I am using:
load data local infile './test.csv' into table TEST fields terminated by '\t'
lines terminated by '\n'
IGNORE 1 LINES
(id,@creation_date)
SET
creation_date = nullif(@creation_date,'NULL');
But unfortunately the NULL value (String) is not interpreted and set to a NULL in the column. Instead I get a warning about data truncation and a default date is inserted 0000-00-00....
How can I check: Is String = "NULL" then insert NULL into column?
Upvotes: 3
Views: 7739
Reputation: 1931
The documentation has rules to how NULL is interpreted in the file depending on you query fields and lines used, in simple terms:
- If
FIELD
andLINES
is default values in your query use\N
(NO QUOTES).- If
FIELD ENCLOSED BY
and/orFIELD ESCAPED BY
is used, use the wordNULL
(NO QUOTES).- With fixed-row format (which is used when
FIELDS TERMINATED BY
andFIELDS ENCLOSED BY
are both empty), NULL is written as an empty string i.e.""
.
Your use case is the first bullet.
**Read more from the docs in the bottom paragraph Handling of NULL values varies according to the FIELDS and LINES options in use:
of the section link above.
Upvotes: 1
Reputation: 982
Beware, it#s so stupid but I managed the error. Since the date is the last column in the row and no '"' are used to split the columns mysql is of cause interpreting the column with a trailing carriage return!
Solution:
load data local infile './test.csv' into table TEST fields terminated by '\t'
lines terminated by '\n'
IGNORE 1 LINES
(id,@creation_date)
SET
creation_date = nullif(@creation_date,'NULL\r');
I know it looks soo dirty!
EDITED: so of course using the line termination for this would be wiser ;)
load data local infile './test.csv' into table TEST fields terminated by '\t'
lines terminated by '\r\n'
IGNORE 1 LINES
(id,@creation_date)
SET
creation_date = nullif(@creation_date,'NULL');
... maybe someone ends up with the same problem and want to follow my path :)
Upvotes: 0
Reputation: 182
You can use "TRAILING NULLCOLS" to insert null values from the file into database.
Ex:
load data
infile 'test1.csv'
APPEND
into table tab1
TRAILING NULLCOLS
(
id integer <data type> TERMINATED BY ',',
creation_date <data type>
)
Upvotes: 0