Click on the banner to learn about and purchase my database training on Azure

Importing CSV Files into the SQL Server Database

Views: 6.225 views
Reading Time: 3 minutes

Hello guys!
Good Morning!

Today I am very excited about this stored procedure that I will present to you, because it really gave me a little work to develop. Of course, you have heard of CSV (Comma-separated values) files, those text files where information is organized using a delimiter, usually comma (,) or semicolon (;).

Well, last week a need arose where I work to import a CSV file into the database, where the columns would have to be created according to the CSV file. To solve this, I created a stored procedure that reads the CSV file, identifies the columns, and dynamically creates a table to store the data coming from CSV.

In the procedure, I also put an optional parameter to inform if the first line of the file is the CSV header. In this case, the first row will not be displayed in the final result and the column heading will dynamically change to the name contained in that column of the header row.

Before going to the code, this procedure uses two other functions that I had already mentioned here on the blog:

UPDATE 20 / 03 / 2017: If you want to use a more robust, complete and more performative solution, check out how to import data from tabular files with CSV using CLR (C #) in the post. SQL Server - How to export and import tabular data files (Ex: CSV) using CLR (C #).

Lets go to what matters. Source code!!

Directions for use:

Original file:

Table imported into database with the above command:

That's it folks!
Do you like it?