简体   繁体   English

将 CSV 文件插入到 SQL 服务器中已有的表中

[英]Insert CSV file to already existing table within SQL Server

I have a.csv file that I must update to my already existing table within SQL Server.我有一个 .csv 文件,我必须将其更新到 SQL 服务器中已有的表。 Is there a query other than a BULK INSERT that I can use for this?除了 BULK INSERT 之外,还有其他查询可以用于此目的吗?

Here is the database and table: Backup Database - dbo.Backup$ table这是数据库和表:备份数据库 - dbo.Backup$ 表

Here is the sample data that is already in the dbo.Backup$ table这是 dbo.Backup$ 表中已有的示例数据

  Location  Name
  ga        John
  pa        Sally

This is the.csv file data: (test1.csv)这是.csv文件数据:(test1.csv)

  Location Name
  ca       Jan
  ky       Bill

Desired output:所需的 output:

  Location  Name
  ga        John
  pa        Sally
  ca        Jan
  ky        Bill

The.csv file has the same columns. .csv 文件具有相同的列。 I just need to update my existing dbo.Backup$ table with the new.csv file.我只需要用新的 .csv 文件更新我现有的 dbo.Backup$ 表。 I am thinking I can perform a BULK INSERT command to do this, however, the column names keep importing as well.我想我可以执行 BULK INSERT 命令来执行此操作,但是,列名也会继续导入。

This is what I am doing:这就是我正在做的:

BULK INSERT test
   FROM 'C:\Test\test1.csv'
WITH
   (
   rowterminator='\n',
   fieldterminator=','
   )

From the documentation文档

Skipping headers is not supported by the BULK INSERT statement. BULK INSERT 语句不支持跳过标头。

What you can do to bypass this:你可以做些什么来绕过这个:

  1. Create a temp table with the same structure,创建一个具有相同结构的临时表,
  2. BULK INSERT into the temp table批量插入临时表
  3. Remove the first row of the temp table删除临时表的第一行
  4. SELECT INTO the "real" table from the temp table. SELECT 进入临时表中的“真实”表。

Or if this is an action you need to do on a regular basis, build an SSIS package to load the CSV into the table.或者,如果这是您需要定期执行的操作,请构建一个 SSIS package 以将 CSV 加载到表中。

You can do OpenRowSet:你可以做 OpenRowSet:

INSERT INTO dbo.Backup$
        
SELECT * from OPENROWSET('Microsoft.ACE.OLEDB.12.0','Excel 12.0; HDR=YES; 
Database=C:\User_Name\file_you_wish_to_insert.xlsx',[Sheet1$]);

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

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