Lynn
Lynn

Reputation: 4408

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. Is there a query other than a BULK INSERT that I can use for this?

Here is the database and table: Backup Database - dbo.Backup$ table

Here is the sample data that is already in the dbo.Backup$ table

  Location  Name
  ga        John
  pa        Sally

This is the .csv file data: (test1.csv)

  Location Name
  ca       Jan
  ky       Bill

Desired output:

  Location  Name
  ga        John
  pa        Sally
  ca        Jan
  ky        Bill

The .csv file has the same columns. I just need to update my existing dbo.Backup$ table with the new .csv file. I am thinking I can perform a BULK INSERT command to do this, however, the column names keep importing as well.

This is what I am doing:

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

Upvotes: 4

Views: 20125

Answers (2)

Lynn
Lynn

Reputation: 4408

You can do 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$]);

Upvotes: 0

Preben Huybrechts
Preben Huybrechts

Reputation: 6141

From the documentation

Skipping headers is not supported by the BULK INSERT statement.

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.

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.

Upvotes: 1

Related Questions