What I need to do is to create a SQL Server Script to insert records from a CSV file to a table. I know that this can be done easily using "BULK Insert".
BULK
INSERT TempTable
FROM 'C:\Records.csv'
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
GO
Unfortunately, the CSV file contains inconsistent qualifiers ("). Some fields may or may not have this qualifiers when the CSV file is created (manually) like the sample below:
10001,LeBron Quitter,CompanyA
10002,"Insane, Charlie",CompanyB
10003,Donald Punk,"CompanyC,CA"
If I use the above code for the said CSV format, there will be errors because:
1. Qualifier will be included in the table (Ex: "Insane)
2. Since comma (,) is the fieldterminator, the 2nd record will be considered as 4 fields.
So I have to think of something else since I don't want to preprocess the CSV file. It came down to this solution - using MICROSOFT.JET.OLEDB.4.0.
INSERT INTO MyRealTable
SELECT * FROM OPENROWSET('MICROSOFT.JET.OLEDB.4.0','Text;Database=C:\Temp\;','SELECT * FROM [Test.csv]')
Note: Before executing the above code be sure to have access right/permission & execute the following:
EXEC
sp_configure 'show advanced options', 1
Reconfigure
EXEC
sp_configure 'Ad Hoc Distributed Queries', 1
Reconfigure
EXEC
sp_configure 'OLE Automation Procedures', 1;
Reconfigure
EXEC
sp_configure 'Agent XPs', 1;
Reconfigure
Questions:
1. Is my solution the right one?
2. Are there any other better solution?
3. Since I'm using MICROSOFT.JET.OLEDB.4 solution, what should be installed/prerequisite?
I'm very open to any suggestion, criticism, or anything because I just want to learn more... Thanks you very much in advance...