I am looking for help to import a .csv
file into SQL Server using BULK INSERT
and I have few basic questions.
Issues:
The CSV file data may have
,
(comma) in between (Ex: description), so how can I make import handling these data?If the client creates the CSV from Excel then the data that have comma are enclosed within
""
(double quotes) [as the below example] so how do the import can handle this?How do we track if some rows have bad data, which import skips? (does import skips rows that are not importable)
Here is the sample CSV with header:
Name,Class,Subject,ExamDate,Mark,Description
Prabhat,4,Math,2/10/2013,25,Test data for prabhat.
Murari,5,Science,2/11/2013,24,"Test data for his's test, where we can test 2nd ROW, Test."
sanjay,4,Science,,25,Test Only.
And SQL statement to import:
BULK INSERT SchoolsTemp
FROM 'C:\CSVData\Schools.csv'
WITH
(
FIRSTROW = 2,
FIELDTERMINATOR = ',', --CSV field delimiter
ROWTERMINATOR = '\n', --Use to shift the control to next row
TABLOCK
)
The best, quickest and easiest way to resolve the comma in data issue is to use Excel to save a comma separated file after having set Windows' list separator setting to something other than a comma (such as a pipe). This will then generate a pipe (or whatever) separated file for you that you can then import. This is described here.
Firs you need to import CSV file into Data Table
Then you can insert bulk rows using SQLBulkCopy
Because they do not use the SQL import wizard, the steps would be as follows:
Right click on the database in the option tasks to import data,
Once the wizard is open, we select the type of data to be implied. In this case it would be the
We select the CSV file, you can configure the data type of the tables in the CSV, but it is best to bring it from the CSV.
Depending on our type of authentication we select it, once this is done, a very important option comes.
(usually not starting from 1), instead if we have a column with the id in the CSV we select the enable id insert, the next step is to end the wizard, we can review the changes here.
On the other hand, in the following window may come alerts, or warnings the ideal is to ignore this, only if they leave error is necessary to pay attention.
This link has images.
You should use FORMAT = 'CSV', FIELDQUOTE = '"' options:
Here's how I would solve it:
Just Save your CSV File as a XLS Sheet in excel(By Doing so, you wouldn't have to worry about delimitiers. Excel's spreadsheet format will be read as a table and imported directly into a SQL Table)
Import the File Using SSIS
Write a Custom Script in the import manager to omit/modify the data you're looking for.(Or run a master script to scrutinize the data you're looking to remove)
Good Luck.
Import a CSV file into a database by SQL Server Management Studio.
Reference