Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / SQL-Server / SQL-Server-2014

Import CSV or txt File Into SQL Server Using Bulk Insert.

4.93/5 (5 votes)
21 May 2014CPOL 163K  
Import CSV or txt File Into SQL Server Using Bulk Insert.

Introduction

I am showing here How to import CSV or txt file into SQL Server Database Table. How to load comma delimited file into SQL Server.

Using the code

CSV stands for Comma Separated Values, sometimes also called Comma Delimited Values. and
if loading txt file then file should have Comma Delimited Values. and file should be like

Image 1

Here is the script to create table-:

SQL
CREATE TABLE Employee(
Id int,
Name VARCHAR(100),
Designation VARCHAR(100)
)

I Created a txt and a CSV file in location 'F:\\MyPublis\\ with the txt file name is TestToInsert.txt
Now run following script to load all the data from txt file to database table. If there is any error in any row it will be not inserted but other rows will be inserted.
I created Id column as integer in the Emloyee table, if there is any row in my file having first part of the data as a string means that will go to Id column then it will not insert that row and will continew with next row.

SQL
BULK
INSERT Employee
FROM 'F:\\MyPublis\\TestToInsert.txt' --location with filename
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
GO

Now see data in table -:

SQL
SELECT *FROM Employee

Image 2

execute same script for the CSV file.

CSV file having the data -:

10, Siv_CSV, CEO
11, Brijendra_CSV, Operatore
12, Micro, Company

SQL
BULK 
INSERT Employee
FROM 'F:\\MyPublis\\CSVTest.csv' --location with filename
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
GO
SELECT *FROM Employee

output will be-:

Image 3

History

Keep a going.....

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)