views:

28

answers:

2

I have a csv file that has column values enclosed within double quotes.

I want to import a csv file from a network path using an sql statement.

I tried bulk insert. But it imports along with double quotes. Is there any other way to import a csv file into SQL Server 2008 using an sql statement by ignoring the text qualifier double quote?

Thanks -Vivek

+1  A: 

This is a known issue when importing files with text delimiters as the bcp/bulk insert utilities don't allow you to specify a text delimiter. See this link for a good discussion.

Joe Stefanelli
+1  A: 

You could use a non-xml format file to specify a different delimiter per column. For values enclosed with double quotes, and delimited by tabs, the delimiter could be \",\". You'd have to add an initial unused column to capture the first quote. For example, to read this file:

"row1col1","row1col2","row1col3"
"row2col1","row2col2","row2col3"
"row3col1","row3col2","row3col3"

You could use this format file:

10.0
4
1  SQLCHAR 0 50 "\""     0 unused ""
2  SQLCHAR 0 50 "\",\""  1 col1   ""
3  SQLCHAR 0 50 "\",\""  2 col2   ""
4  SQLCHAR 0 50 "\"\r\n" 3 col3   ""

(The number on the first line depends on the SQL Server version. The number on the second line is the number of columns to read. Don't forget to adjust it.)

The bulk insert command accepts a formatfile = 'format_file_path' parameter where you can specify the format file. For example:

BULK INSERT YourTable
FROM 'c:\test\test.csv'
WITH (FORMATFILE = 'c:\test\test.cfmt')

This results in:

select * from YourTable
-->
col1        col2        col3
row1col1    row1col2    row1col3
row2col1    row2col2    row2col3
row3col1    row3col2    row3col3
Andomar
Would this still leave you with a leading double-quote on your first field and a trailing double-quote on your last field?
Joe Stefanelli
@Joe Stefanelli: You can capture the leading quote in an unused field, and the trailing quote in the terminator for the last field. I've tested the example I posted and it works on SQL Server 2008 (which has BCP version 10.0)
Andomar
+1 Nicely done. I wouldn't have thought of using an unused field for that leading quote.
Joe Stefanelli
Hi andomar, thanks a lot
Vivek Chandraprakash
Hi andomar, in my csv some columns will be enclosed within double quotes and some wont be. Is it possible to make this double quote optional?_V
Vivek Chandraprakash
@Vivek Chandraprakash: Don't think so. You could import without the quotes, and remove them like `update YourTable set col1 = substring(col1,2,len(col1)-2) where col1 like '"%"'`
Andomar