Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import CSV into SQL Server (including automatic table creation) [duplicate]

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 before on basis the first row of the CSV files,are the column names.

like image 661
M. X Avatar asked Mar 27 '13 09:03

M. X


People also ask

How can I create a duplicate table in SQL Server?

In Object Explorer, right-click Tables and select New Table. In Object Explorer right-click the table you want to copy and select Design. Select the columns in the existing table and, from the Edit menu, select Copy. Switch back to the new table and select the first row.


2 Answers

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

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.

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/

like image 166
Nenad Zivkovic Avatar answered Sep 21 '22 21:09

Nenad Zivkovic


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 
like image 25
03Usr Avatar answered Sep 22 '22 21:09

03Usr