将 CSV 导入 SQL Server(包括自动创建表)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15655380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 14:29:43  来源:igfitidea点击:

Import CSV into SQL Server (including automatic table creation)

sqlsql-servercsv

提问by M. X

I have several CSV files, which I want to import into an SQL Server database. I know if this is possible with BULK insert, but I want a solution, so that also the import table is automatically created beforeon basis the first row of the CSV files,are the column names.

我有几个CSV 文件,我想将它们导入到SQL Server 数据库中。我知道这是否可以通过 BULK 插入实现,但我想要一个解决方案,以便在 CSV 文件的第一行之前自动创建导入表,即列名。

回答by Nenad Zivkovic

SQL Server Management Studio provides an Import/Export wizard tool which have an option to automatically create tables.

SQL Server Management Studio 提供了一个导入/导出向导工具,可以选择自动创建表。

You can access it by right clicking on the Database in Object Explorer and selecting Tasks->Import Data...

您可以通过右键单击对象资源管理器中的数据库并选择任务-> 导入数据...

From there wizard should be self-explanatory and easy to navigate. You choose your CSV as source, desired destination, configure columns and run the package.

从那里向导应该是不言自明且易于导航的。您选择您的 CSV 作为源、所需目标、配置列并运行包。

If you need detailed guidance, there are plenty of guides online, here is a nice one: http://www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/

如果您需要详细的指导,网上有很多指南,这里有一个不错的指南:http: //www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/

回答by 03Usr

You can create a temp table variable and insert the data into it, then insert the data into your actual table by selecting it from the temp table.

您可以创建一个临时表变量并将数据插入其中,然后通过从临时表中选择数据将数据插入到实际表中。

 declare @TableVar table 
 (
    firstCol varchar(50) NOT NULL,
    secondCol varchar(50) NOT NULL
 )

BULK INSERT @TableVar FROM 'PathToCSVFile' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n')
GO

INSERT INTO dbo.ExistingTable
(
    firstCol,
    secondCol
)
SELECT firstCol,
       secondCol
FROM @TableVar

GO