Estimated reading time: 3 minutes
In many of the SQL programming softwatre tools, there will most likely be an option for you to import your data torugh a screen they have provided.
In SQL Server Management Studio the below screen is available to pick your file to import, and it quickly guides you through the steps.
But what if you wanted to do this through code, as you may have lots of different files to be loaded at different times?
Below we will take you through the steps.
Check the file you want to import
Below we have created a CSV file, with the relevant headers and data. It is important to have the headers correct as this is what we will use in a step further down.
Create the code that will import the data
drop table sales.dbo.test_import_csv; ===> drops the existing table, to allow a refreshed copy be made. create table sales.dbo.test_import_csv( customer_name varchar(10), age int, place_of_birth varchar(10)); ===> These steps allow you to recreate the table with the column names and data type. insert into sales.dbo.test_import_csv select * FROM OPENROWSET(BULK 'C:\Users\haugh\OneDrive\dataanalyticsireland\YOUTUBE\SQL\how_to_import_a_csv _file_in_sql\csv_file_import.csv', formatfile = 'C:\Users\haugh\OneDrive\dataanalyticsireland\YOUTUBE\SQL\how_to_import_a_csv _file_in_sql\csv_file_import_set.txt', FIRSTROW=2, FORMAT='CSV' ) as tmp ===> These lines open the file, read in the data to the table created.
There are two important parts to the above code:
(A) OPENROWSET – This enables the connection to the CSV, read it and then insert the information into the database table.
(B) Formatfile – This is an important part of the code. Its purpose is to tell openrowset how many columns are in the CSV file. Its contents are below:
As can bee seen it outlines each column within the file and its name, and the exact column name in the header.
Also the last line indicates that this is the last column and the program should only read as far as this.
Running the code and the output
When the code is run, the following is the output:
Eleven rows where inserted, these are the now of rows in the CSV, excluding the headers.
The database table was created:
And finally, the table was populated with the data:
So in summary we have demonstrated that the ability to easily import a CSV file, with the above steps.
In essence you could incorporate this into an automated process.