我想知道在sqlserver中导入CSV文件的正确方法是什么,sqlserver中的数据如下
GLMAC1,GLMAC2,GLMAC3,GLYR,GLMON,GLSUB,GLTREF,GLDATE,GLDESC,GLAMT,GLSRC,GLBTCH,GLMCMP
1 ,32 ,110 ,13 ,1 ,0 ,171406200A ,120801 ,MH YM PANT W/DRAWS ,-.15 ,NOIA,ITCGR119,1
1 ,32 ,110 ,13 ,1 ,13402747 ,446286 ,120801 ,URBAN 1714062 ,15.13 ,904 ,ITCGR11B,1
1 ,32 ,110 ,13 ,1 ,0 ,172830300A ,120801 ,OP 5+2 SOCKS ,-.39 ,NOIA,ITCGR165,1
1 ,32 ,110 ,13 ,1 ,13402802 ,338728 ,120801 ,INDUSTRIES 1728303 ,39.28 ,904 ,ITCGR16C,1
1 ,32 ,110 ,13 ,1 ,0 ,171450700A ,120801 ,FA M.3PK FASHION S ,-.08 ,NOIA,ITCGR19Z,1
1 ,32 ,110 ,13 ,1 ,13402845 ,121811 ,120801 ,BO & CO... 1714507 ,7.49 ,904 ,ITCGR1B0,1 大约有5000万行,我想在Server中导入这些数据,但是我注意到,在导入数据之后,一些列被转移到另一个列,这可能是因为第9列中可能有一些逗号(,)值,而SQL server将其作为(,)分隔符。
是否有一种方法可以在sql服务器中插入数据而不出现错误,或者在插入之前清除CSV文件。该文件的大小约为8GB,我必须使用010Editor在编辑器或任何可用的软件中打开该文件,这些软件可以帮助我了解第9列中有哪些值(,),以便手动删除逗号。
发布于 2015-10-21 22:26:53
此C#代码将读取该文件,在第9个字段附近添加一对"s“来分隔它,并将其写入一个新的输出文件。
像这样一条线
1 ,32 ,110 ,13 ,1 ,0 ,171406200A ,120801 ,MH YM,PANT W/DRAWS ,-.15 ,NOIA,ITCGR119,1 将以下列方式写入输出文件:
1 ,32 ,110 ,13 ,1 ,0 ,171406200A ,120801 ,"MH YM,PANT W/DRAWS ",-.15 ,NOIA,ITCGR119,1 如果文本列被正确分隔,它将适合导入到Server中。
守则如下:
using System.Text.RegularExpressions;
void Main() {
Regex regex = new Regex("(.*?,.*?,.*?,.*?,.*?,.*?,.*?,.*?,)(.*)(,.*?,.*?,.*?,)", RegexOptions.CultureInvariant | RegexOptions.Compiled);
string regexReplace = "$1\"$2\"$3";
// The file to read - change this to your location
var iStream = new FileStream(@"R:\FILE.CSV", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
// The file to write
var oStream = new FileStream(@"R:\FIXEDFILE.CSV", FileMode.Create, FileAccess.Write, FileShare.Read);
int lineNo=0;
var sw = new System.IO.StreamWriter(oStream);
var sr = new System.IO.StreamReader(iStream);
while(!sr.EndOfStream) {
lineNo++;
string line=sr.ReadLine();
if (!regex.IsMatch(line)) {
// Bad lines don't get written to the output file
Console.WriteLine("Line {0} is bad - does not match the expected format:\n\r {1}", lineNo, line);
} else {
// Write the line with the ""'s around the 9th field
sw.WriteLine(regex.Replace(line,regexReplace));
}
if (lineNo%10000==0) Console.WriteLine("{0} lines processed", lineNo);
}
sr.Close();
sw.Close();
Console.WriteLine("Finished. Written {0} lines", lineNo);
}https://stackoverflow.com/questions/33269065
复制相似问题