Inserting Dates with BULK INSERT - sql

I have a CSV file, which contains three dates:
'2010-07-01','2010-08-05','2010-09-04'
When I try to bulk insert them...
BULK INSERT [dbo].[STUDY]
FROM 'StudyTable.csv'
WITH
(
MAXERRORS = 0,
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
I get an error:
Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 1 (CREATED_ON).
So I'm assuming this is because I have an invalid date format. What is the correct format to use?
EDIT
CREATE TABLE [dbo].[STUDY]
(
[CREATED_ON] DATE,
[COMPLETED_ON] DATE,
[AUTHORIZED_ON] DATE,
}

You've got quotes (') around your dates. Remove those and it should work.

Does your data file have a header record? If it does, obviously your table names will not be the correct data type, and will fail when SQL Server tries to INSERT them into your table. Try this:
BULK INSERT [dbo].[STUDY]
FROM 'StudyTable.csv'
WITH
(
MAXERRORS = 0,
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n',
FIRSTROW = 2
)
According to MSDN the BULK INSERT operation technically doesn't support skipping header records in the CSV file. You can either remove the header record or try the above. I don't have SQL Server in front of me at the moment, so I have not confirmed this works. YMMV.

Related

How to insert null value when datatype error is fired using Bulk Insert?

I'm using Bulk Insert command in T-SQL cause I have a too big csv file. This file has fields that use numeric datatypes like float, but in these fields sometimes there are data with strings like "S/N".
So, how can I force that fields to NULL when I get an string value while I'm inserting?
Now I'm using this command, can you help me?
BULK INSERT [CUBOS_FINDIRECT].[dbo].[ListadoRobinsonTXT]
FROM '\\10.0.20.17\d$\listadoRobinson\listadoRobinsonDef.csv'
WITH
(
FIRSTROW = 2,
MAXERRORS = 0,
FIELDTERMINATOR = ';',
ROWTERMINATOR = '\n'
)
Thank you in advance so much.

Bulk insert error, when loading date format

I'm receiving a lot of .csv files that I need to bulk insert into a SQL table.
In the csv file the date format is in YYYY-MM-DD and a seperate column for time which is in format HH:MM:SS.
"2016-11-24";"01:00:16"
In my table I created the two columns as a date datatype and a time datatype and using this piece of code to insert:
BULK
INSERT [dbo].[table_name]
FROM 'filepath'
WITH
(
FIRSTROW = 2,
FIELDTERMINATOR = ';',
ROWTERMINATOR = '\n'
)
But I get this error:
Msg 4864, Level 16, State 1, Line 37
Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 2, column 1 (date).
If I use a normal insert into statement it works...
First check your physical table date and time columns data type. It has datetime format, which means first you move all .csv file data to a temporary table with varchar datatype. After inserted in temporary table then move to physical table with use of datetime conversion.

error Bulk load data conversion error (truncation) when inserting data from a text file

got about 20 to 50 rows in a text file to insert into my database 'bourse' using sql server management studio 2012 my database 'bourse contains certain number of tables for example i have the table IB_emetteur it has 3 attributes (c_emetteur , libelle , mnemes )
and i have the data in a text file structured like this :
1,UFI,U.F.I
2,TSI, T.S.I
3,ADAY,A.Day
5,CAPITAL,C.PITAL
7,COFCAP,COFjuil
8,SFI,SUIhyuo
9,AFC,A.KIYUI
13,CGI,chakoqguio
14,BNAC,banque hyuijsii
i have to insert this data in my table so i used this query :
bulk insert [dbo].[IB_Emetteur]
from 'C:\Users\Manu\Documents\GL5\Finance\liste_emetteur.txt'
with (fieldterminator = ',', rowterminator = '\n')
go
but i got this error
Bulk load data conversion error (truncation) for row 1, column 2 (mnemes)
Try
bulk insert [dbo].[IB_Emetteur]
from 'C:\Users\Manu\Documents\GL5\Finance\liste_emetteur.txt'
with (fieldterminator = ',', rowterminator = '\n',FIRSTROW = 2)
go

Bulk insert with a different schema

I am trying to get data from a csv file with the following data.
Station code;DateBegin;DateEnd
01;20100214;20100214
02;20100214;20100214
03;20100214;20100214
I am trying bulk insert as
BULK INSERT dbo.#tmp_station_details
FROM 'C:\station.csv'
WITH (
FIELDTERMINATOR ='';'',
FIRSTROW = 2,
ROWTERMINATOR = ''\n''
)
But the table tmp_station_details has one extra column as Priority.
Its schema is like
[Station code] [Priority] [DateBegin] [DateEnd]
Now is this possible to bulk insert without altering the schema of the table.
Add FORMATFILE = 'format_file_path' to your "with" block. Refer to BOL: using a format file to skip a table column for an example.

SQL Bulk Insert with FIRSTROW parameter skips the following line

I can't seem to figure out how this is happening.
Here's an example of the file that I'm attempting to bulk insert into SQL server 2005:
***A NICE HEADER HERE***
0000001234|SSNV|00013893-03JUN09
0000005678|ABCD|00013893-03JUN09
0000009112|0000|00013893-03JUN09
0000009112|0000|00013893-03JUN09
Here's my bulk insert statement:
BULK INSERT sometable
FROM 'E:\filefromabove.txt
WITH
(
FIRSTROW = 2,
FIELDTERMINATOR= '|',
ROWTERMINATOR = '\n'
)
But, for some reason the only output I can get is:
0000005678|ABCD|00013893-03JUN09
0000009112|0000|00013893-03JUN09
0000009112|0000|00013893-03JUN09
The first record always gets skipped, unless I remove the header altogether and don't use the FIRSTROW parameter. How is this possible?
Thanks in advance!
I don't think you can skip rows in a different format with BULK INSERT/BCP.
When I run this:
TRUNCATE TABLE so1029384
BULK INSERT so1029384
FROM 'C:\Data\test\so1029384.txt'
WITH
(
--FIRSTROW = 2,
FIELDTERMINATOR= '|',
ROWTERMINATOR = '\n'
)
SELECT * FROM so1029384
I get:
col1 col2 col3
-------------------------------------------------- -------------------------------------------------- --------------------------------------------------
***A NICE HEADER HERE***
0000001234 SSNV 00013893-03JUN09
0000005678 ABCD 00013893-03JUN09
0000009112 0000 00013893-03JUN09
0000009112 0000 00013893-03JUN09
It looks like it requires the '|' even in the header data, because it reads up to that into the first column - swallowing up a newline into the first column. Obviously if you include a field terminator parameter, it expects that every row MUST have one.
You could strip the row with a pre-processing step. Another possibility is to select only complete rows, then process them (exluding the header). Or use a tool which can handle this, like SSIS.
Maybe check that the header has the same line-ending as the actual data rows (as specified in ROWTERMINATOR)?
Update: from MSDN:
The FIRSTROW attribute is not intended
to skip column headers. Skipping
headers is not supported by the BULK
INSERT statement. When skipping rows,
the SQL Server Database Engine looks
only at the field terminators, and
does not validate the data in the
fields of skipped rows.
I found it easiest to just read the entire line into one column then parse out the data using XML.
IF (OBJECT_ID('tempdb..#data') IS NOT NULL) DROP TABLE #data
CREATE TABLE #data (data VARCHAR(MAX))
BULK INSERT #data FROM 'E:\filefromabove.txt' WITH (FIRSTROW = 2, ROWTERMINATOR = '\n')
IF (OBJECT_ID('tempdb..#dataXml') IS NOT NULL) DROP TABLE #dataXml
CREATE TABLE #dataXml (ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED, data XML)
INSERT #dataXml (data)
SELECT CAST('<r><d>' + REPLACE(data, '|', '</d><d>') + '</d></r>' AS XML)
FROM #data
SELECT d.data.value('(/r//d)[1]', 'varchar(max)') AS col1,
d.data.value('(/r//d)[2]', 'varchar(max)') AS col2,
d.data.value('(/r//d)[3]', 'varchar(max)') AS col3
FROM #dataXml d
You can use the below snippet
BULK INSERT TextData
FROM 'E:\filefromabove.txt'
WITH
(
FIRSTROW = 2,
FIELDTERMINATOR = '|', --CSV field delimiter
ROWTERMINATOR = '\n', --Use to shift the control to next row
ERRORFILE = 'E:\ErrorRows.csv',
TABLOCK
)
To let SQL handle quote escape and everything else do this
BULK INSERT Test_CSV
FROM 'C:\MyCSV.csv'
WITH (
FORMAT='CSV'
--FIRSTROW = 2, --uncomment this if your CSV contains header, so start parsing at line 2
);
In regards to other answers, here is valuable info as well:
I keep seeing this in all answers: ROWTERMINATOR = '\n'
The \n means LF and it is Linux style EOL
In Windows the EOL is made of 2 chars CRLF so you need ROWTERMINATOR = '\r\n'
Given how mangled some data can look after BCP importing into SQL Server from non-SQL data sources, I'd suggest doing all the BCP import into some scratch tables first.
For example
truncate table Address_Import_tbl
BULK INSERT dbo.Address_Import_tbl
FROM 'E:\external\SomeDataSource\Address.csv'
WITH (
FIELDTERMINATOR = '|', ROWTERMINATOR = '\n', MAXERRORS = 10
)
Make sure all the columns in Address_Import_tbl are nvarchar(), to make it as agnostic as possible, and avoid type conversion errors.
Then apply whatever fixes you need to Address_Import_tbl. Like deleting the unwanted header.
Then run a INSERT SELECT query, to copy from Address_Import_tbl to Address_tbl, along with any datatype conversions you need. For example, to cast imported dates to SQL DATETIME.