简体   繁体   English

将 csv 导入 SQL Server 表

[英]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.我遇到的问题是我需要将一个.csv文件导入到 SQL Server 表中以进行进一步处理,但其中一列可能有一个“,”,这会破坏导入。

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. PS:请记住,我正在重新学习东西,所以你可能不得不“愚蠢”地提出任何建议。 ;) ;)

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:如果您使用 c#,您实际上可以做的是准确识别逗号的位置,例如,如果您有这样的表:

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:如果您可以看到通常有 3 列以逗号分隔,并且在第 3 列中 Peach 单词中有一个额外的逗号,因此如果逗号始终出现在第二列,您可以计算每行的单词数:

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: //通常它总是计数 3,但是当它计数为 4 时,您可以在该列上使用 if 条件:

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!我的意思是这只是想法和快速答案,但取决于您的操作方式,您只需要找到该 CSV 的正确模式,以便您弄清楚如何解决!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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