简体   繁体   中英

Import csv into SQL Server table

I was a developer a long time ago and moved into a management position but back to doing some light development with a new role.

The problem I have is that I need to import a .csv file into a SQL Server table for further processing which I have working but one column may have a "," in it that is blowing up the import.

I know it works whenever I force the "," to be removed but need to be able to do this programmatically. The file comes from an external source so unfortunately I don't have the ability to have the source corrected or to place " " around the column as a delimiter.

Any help or suggestion would be appreciated.

PS: please keep in mind that I'm re-learning stuff so you may have to "dumb" down any suggestions. ;)

steve

What you actually can do if you are working with c# is to identify exactly where the comma is, for example if you have a table like this:

Apple,Peach,Raspberry
Apple,Banana,grape
Tomato,Pe,ch,Raspberry

if you can see usually there is 3 columns separated by comma, and right in the 3th column there is an extra comma in the Peach word, so if the comma always appears on the second column you can count the words per line:

var contents = File.ReadAllText(filename).Split('\n');
//you can use linq
var csv = from line in contents select line.Split(',').ToArray();
var count = contents.Split(',').Length; 

//Usually it will always count 3, but when it counts 4 then you can use an if condition, right on that colum:

if(count > 3){

col2 = csv[1] + csv[2]

}

I mean this is just the Idea and quick answer, but depends of the way you are doing it, you just have to find the right pattern of that CSV so you figure how to work around!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM