Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create and populate a table in a single step as part of a CSV import operation?

I am looking for a quick-and-dirty way to import CSV files into SQL Server without having to create the table beforehand and define its columns.

Each imported CSV would be imported into its own table.

We are not concerned about data-type inferencing. The CSV vary in structure and layout, and all of them have many many columns, yet we are only concerned with a few of them: street addresses and zipcodes. We just want to get the CSV data into the SQL database quickly and extract the relevant columns.

I'd like to supply the FieldTerminator and RowTerminator, point it at the CSV, and have the utility do the rest. Is there any way to create the table and populate it, all in one step, using BULK INSERT and/or OpenRowset(BULK ... ) ?

like image 504
Tim Avatar asked May 02 '12 17:05

Tim


People also ask

How do I import a CSV file into a table?

Select the table or use the New option to create a new table for importing the csv file. While creating a new table, we need to mention the columns and their data types that correspond to the columns in the file. You can also create the table and database while importing the csv file. Selecting Import menu.


1 Answers

Referencing SQLServerPedia, I think this will work:

sp_configure 'show advanced options', 1;
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO

select TerritoryID
      ,TotalSales
      ,TotalCost
INTO CSVImportTable
from openrowset('MSDASQL'
               ,'Driver={Microsoft Access Text Driver (*.txt, *.csv)}'
               ,'select * from C:\csvtest.CSV')
like image 67
TyT Avatar answered Oct 08 '22 19:10

TyT