Importing a CSV(Comma Separated File) in SQL server is a very common task, and most of us use the Import /Export feature of SQL server to do this. Import/Export feature has SSIS (SQL Server Integration Services) as it backbone and works great with most of the Databases, file types etc.
But today we are going to import a CSV file in SQL server through simple SQL queries. Following are the only two steps to follows for a loading a CSV file in SQL Server:
- Create a table, with all the columns you need to import from CSV file.
- Next use Bulk Insert query to load all the data in SQL Server table create in step 1.
Example
CREATE TABLE CSV_LOAD
(
ID INT,
NAME VARCHAR(40),
CLASS VARCHAR(40)
)
Our CSV file contains these values:
1,NAUMAN,BSC
2,RIZWAN,MBA
3,FURQAN,A LEVELS
Now the main part for Bulk Insert
BULK INSERT CSV_LOAD
FROM ‘c:\csvload.csv’
WITH
(
FIELDTERMINATOR = ‘,’,
ROWTERMINATOR = ‘\n’
)
Thats it.