SQL批量插入CSV

时间:2013-02-20 07:26:35

标签: sql-server-2008 csv bulkinsert

我有一个csv逗号分隔文件,其中包含以下格式的数十万条记录:

3212790556,1,0.000000,,0
3212790557,2,0.000000,,0

现在使用SQL Server导入平面文件方法只是花花公子。我可以编辑sql,以便表名和列名是有意义的。另外,我还将数据类型从默认的varchar(50)编辑为int或decimal。这一切都很好,sql import能够成功导入。

但是我无法使用批量插入查询执行相同的任务,如下所示:

BULK
INSERT temp1
FROM 'c:\filename.csv'
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
GO

此查询返回以下3个错误,我不知道如何解决:

Msg 4866, Level 16, State 1, Line 1
The bulk load failed. The column is too long in the data file for row 1, column 5. Verify that the field terminator and row terminator are specified correctly.
Msg 7399, Level 16, State 1, Line 1
The OLE DB provider "BULK" for linked server "(null)" reported an error. The provider did not give any information about the error.
Msg 7330, Level 16, State 2, Line 1
Cannot fetch a row from OLE DB provider "BULK" for linked server "(null)".

我的应用程序的目的是在一个文件夹中有多个csv文件,所有这些文件都需要在一个表中,以便我可以查询值的总和。目前我正在考虑用C#编写一个程序,它将循环执行BULK插入(根据文件数量),然后返回我的结果。我猜我不需要编写代码,我只能写一个完成所有这一切的脚本 - 任何人都可以引导我走向正确的道路:)

非常感谢。

编辑:刚添加

ERRORFILE = 'C:\error.log'

到查询,我插入了5221行。有时它的5222有时会是5222,但它只是失败超过这一点。不知道什么是问题??? CSV完全没问题。

1 个答案:

答案 0 :(得分:2)

SOB。 WTF !!!

我不能相信用ROWTERMINATOR中的“0x0A”代替\ n工作!!!我的意思是认真。我刚刚尝试过它并且有效。 WTF时刻!!完全。

然而有趣的是,SQL Import向导也只需要导入大约10秒。导入查询花了一分多钟。任何猜测??