Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert CSV file to already existing table within SQL Server

Tags:

sql

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=','
   )
like image 404
Lynn Avatar asked May 29 '26 14:05

Lynn


1 Answers

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.

like image 54
Preben Huybrechts Avatar answered May 31 '26 04:05

Preben Huybrechts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!