>> GreenByte.info By Nick Tong (quiksilv) | Supported by: TalkWebSolutions.co.uk

Bulk insert a CSV/excel file

A lot of the time i get given data in excel formats that i need to insert into tables. The quickest way (I find) to do this is to save the excel as a CSV, upload the file to the same place SQL server and then run this script:

BULK INSERT MyTableName
FROM 'c:`myPath\myFile.csv' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n', FIRSTROW = 2)

Things to note:

You need to create your table structure first.
This code 'WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n', FIRSTROW = 2)' tells SQL to use commas as the delimiter, use line returns and the row end and lastly to ignore the first line of your CSV file (normally the excel headers).
Make sure you have full table permissions.
SQL gets upset if your fields had odd data i.e. single quotes.

If you have another way of doing this then I'd be interested in hearing about it.


 
Comments
rg's Gravatar Thanks quiksilv

Here's a way to bulk insert from a dataset to an sql database :
http://www.dataportweb.com/post/Sql-bulk-insert-an...
# Posted By rg | 18/09/08 17:38 | Report abusive comment
BlogCFC was created by Raymond Camden. This blog is running version 5.5.1.