我正在寻求帮助,使用BULK INSERT将.csv文件导入SQL Server,我有一些基本的问题。

问题:

CSV文件的数据可能有,(逗号)之间(Ex: description),那么我如何使导入处理这些数据? 如果客户端从Excel中创建CSV,那么有逗号的数据被括在“”(双引号)[如下例],那么导入如何处理这一点? 我们如何跟踪某些行是否有坏数据,哪些导入被跳过?(导入会跳过不可导入的行)

下面是带标题的CSV示例:

Name,Class,Subject,ExamDate,Mark,Description
Prabhat,4,Math,2/10/2013,25,Test data for prabhat.
Murari,5,Science,2/11/2013,24,"Test data for his's test, where we can test 2nd ROW, Test."
sanjay,4,Science,,25,Test Only.

和SQL语句导入:

BULK INSERT SchoolsTemp
FROM 'C:\CSVData\Schools.csv'
WITH
(
    FIRSTROW = 2,
    FIELDTERMINATOR = ',',  --CSV field delimiter
    ROWTERMINATOR = '\n',   --Use to shift the control to next row
    TABLOCK
)

当前回答

All of the answers here work great if your data is "clean" (no data constraint violations, etc.) and you have access to putting the file on the server. Some of the answers provided here stop at the first error (PK violation, data-loss error, etc.) and give you one error at a time if using SSMS's built in Import Task. If you want to gather all errors at once (in case you want to tell the person that gave you the .csv file to clean up their data), I recommend the following as an answer. This answer also gives you complete flexibility as you are "writing" the SQL yourself.

注意:我将假设您运行的是Windows操作系统,并且能够访问Excel和SSMS。如果没有,我相信你可以调整这个答案来满足你的需求。

Using Excel, open your .csv file. In an empty column you will write a formula that will build individual INSERTstatements like =CONCATENATE("INSERT INTO dbo.MyTable (FirstName, LastName) VALUES ('", A1, "', '", B1,"')", CHAR(10), "GO") where A1 is a cell that has the first name data and A2 has the last name data for example. CHAR(10) adds a newline character to the final result and GO will allow us to run this INSERT and continue to the next even if there are any errors. Highlight the cell with your =CONCATENATION() formula Shift + End to highlight the same column in the rest of your rows In the ribbon > Home > Editing > Fill > Click Down This applies the formula all the way down the sheet so you don't have to copy-paste, drag, etc. down potentially thousands of rows by hand Ctrl + C to copy the formulated SQL INSERT statements Paste into SSMS You will notice Excel, probably unexpectedly, added double quotes around each of your INSERT and GO commands. This is a "feature" (?) of copying multi-line values out of Excel. You can simply find and replace "INSERT and GO" with INSERT and GO respectively to clean that up. Finally you are ready to run your import process After the process completes, check the Messages window for any errors. You can select all the content (Ctrl + A) and copy into Excel and use a column filter to remove any successful messages and you are left with any and all the errors.

这个过程肯定会比这里的其他答案花费更长的时间,但是如果您的数据是“脏的”并且充满SQL违规,您至少可以一次性收集所有错误并将它们发送给提供数据的人(如果您的场景是这样的话)。

其他回答

从2013-11-05如何使用SQL Server Management Studio将CSV文件导入到数据库中:

First create a table in your database into which you will be importing the CSV file. After the table is created: Log into your database using SQL Server Management Studio Right click on your database and select Tasks -> Import Data... Click the Next > button For the Data Source, select Flat File Source. Then use the Browse button to select the CSV file. Spend some time configuring how you want the data to be imported before clicking on the Next > button. For the Destination, select the correct database provider (e.g. for SQL Server 2012, you can use SQL Server Native Client 11.0). Enter the Server name; Check Use SQL Server Authentication, enter the User name, Password, and Database before clicking on the Next > button. On the Select Source Tables and Views window, you can Edit Mappings before clicking on the Next > button. Check the Run immediately check box and click on the Next > button. Click on the Finish button to run the package.

因为他们不使用SQL导入向导,步骤如下:

右键单击任务选项中的数据库导入数据, 一旦向导打开,我们选择要隐含的数据类型。在这种情况下,它是

平面文件源

我们选择CSV文件,您可以配置CSV中表的数据类型,但最好是从CSV中带来。

单击Next并选择最后一个选项

SQL客户机

根据我们选择的身份验证类型,一旦完成,就会出现一个非常重要的选项。

我们可以在CSV中定义表的id(建议CSV中的列应该与表中的字段相同)。在Edit Mappings选项中,我们可以看到带有电子表格列的每个表的预览,如果我们希望向导在默认情况下插入id,则不勾选该选项。

启用id插入

(通常不是从1开始),相反,如果我们在CSV中有一个id列,我们选择启用id插入,下一步是结束向导,我们可以在这里检查更改。

另一方面,在下面的窗口中可能会出现警报,或警告,理想的是忽略这一点,只有当他们留下错误时才有必要注意。

这个链接有图片。

Import the file into Excel by first opening excel, then going to DATA, import from TXT File, choose the csv extension which will preserve 0 prefixed values, and save that column as TEXT because excel will drop the leading 0 otherwise (DO NOT double click to open with Excel if you have numeric data in a field starting with a 0 [zero]). Then just save out as a Tab Delimited Text file. When you are importing into excel you get an option to save as GENERAL, TEXT, etc.. choose TEXT so that quotes in the middle of a string in a field like YourCompany,LLC are preserved also...

BULK INSERT dbo.YourTableName
FROM 'C:\Users\Steve\Downloads\yourfiletoIMPORT.txt'
WITH (
FirstRow = 2, (if skipping a header row)
FIELDTERMINATOR = '\t',
ROWTERMINATOR   = '\n'
)

我希望我可以使用FORMAT和Fieldquote功能,但在我的SSMS版本中似乎不支持

我知道这不是上述问题的确切解决方案,但对我来说,当我试图将数据从位于单独服务器上的一个数据库复制到我的本地时,这是一场噩梦。

我试图通过首先从服务器导出数据到CSV/txt,然后将其导入到我的本地表来做到这一点。

两种解决方案:写下查询以导入CSV或使用SSMS导入数据向导总是会产生错误(错误非常普遍,说明存在解析问题)。虽然我没有做任何特别的事情,只是导出到CSV,然后试图将CSV导入到本地DB,错误总是存在。

我试着查看映射部分和数据预览,但总是一团乱。我知道主要的问题是来自一个表列,其中包含JSON和SQL解析器处理错误。

所以最终,我想到了一个不同的解决方案,并想要分享它,以防其他人有类似的问题。


我所做的是在外部服务器上使用了导出向导。

下面是重复相同过程的步骤: 1)右键单击数据库,选择Tasks -> Export Data…

2)当向导打开时,选择“下一步”,在“数据源”的位置选择“SQL Server Native Client”。

在外部服务器的情况下,您很可能必须选择“使用SQL Server身份验证”的“身份验证模式:”。

3)点击下一步后,你必须选择目的地。 为此,再次选择“SQL Server Native Client”。 这一次,您可以提供本地(或其他外部DB) DB。

4)点击Next按钮后,你有两个选择,要么将整个表从一个DB复制到另一个DB,要么写下查询来指定要复制的确切数据。 在我的例子中,我不需要整个表(它太大了),而只是其中的一部分,所以我选择了“写一个查询来指定要传输的数据”。

我建议在使用Wizard之前,在一个单独的查询编辑器上写下并测试该查询。

5)最后,您需要指定将在其中选择数据的目标表。

我建议保留为[dbo]。[Query]或一些自定义表名,以防导出数据时会出错,或者如果您不确定数据,并希望在移动到所需的确切表之前进一步分析它。

现在通过点击下一步/完成按钮直接到向导的末尾。

我知道有公认的答案,但我仍然想分享我的场景,也许能帮助人们解决他们的问题 工具

ASP。网 Ef码优先法 地对地导弹 EXCEL

场景 我正在加载数据集,它是CSV格式的,稍后将在视图中显示 我试图使用散装装载,但我无法装载散装装载正在使用

FIELDTERMINATOR = ','

Excel细胞也在使用, 然而,我也不能直接使用平面文件源,因为我使用的是代码优先的方法,并且只在SSMS DB中制作模型,而不是在我后来必须使用属性的模型中。

解决方案

我使用平面文件源,并从CSV文件制作DB表(右键单击SSMS中的DB ->导入平面文件->选择CSV路径,并按照指示进行所有设置) 在Visual Studio中创建模型类(你必须保持所有的数据类型和名称与sql中加载的CSV文件相同) 在NuGet包控制台使用Add-Migration 更新数据库