Reading a delimited text file into SQL Server table

Hello,

I'm trying to find the best way to read a pipe delimited flat file into a SQL Server table.

Thank you.
rkellowAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
k_murli_krishnaConnect With a Mentor Commented:
You can do:

A) Using BULK INSERT

BULK INSERT <table_name> FROM 'D:\somedata.txt' WITH
(
FIELDTERMINATOR = '|',
ROWTERMINATOR='\n'
)

B) Using LOAD DATA

LOAD DATA LOCAL INFILE '/importfile.csv'
INTO TABLE <table_name>
FIELDS TERMINATED BY '|'
LINES TERMINATED BY '\n'
(field1, filed2, field3);

This loads data into these 3 fields. If you want to load for whole table, omit this.

C) Using bcp

Type bcp -h at command line for all options.

C:\>bcp inventory.dbo.fruits in "C:\fruit\inventory.txt" -c  -t '|' -T
Add/remove/Modify options if required.

D) Using OPENROWSET

INSERT INTO myTable(FileName, FileType, Document)
   SELECT 'Text1.txt' AS FileName,
      '.txt' AS FileType,
      * FROM OPENROWSET(BULK N'C:\Text1.txt', SINGLE_BLOB) AS Document
GO

Try including all columns instead of other than NULL columns or NOT NULL columns with DEFAULT value.
0
 
Raja Jegan RSQL Server DBA & ArchitectCommented:
Just use Import/Export Wizard of SQL Server to import records into your table from the Pipe delimited flat file..
If not, then you can use either BCP or OPENROWSET to insert records from the flat file..
0
 
rkellowAuthor Commented:
Thank you.  I neglected to say that I need to select only certain fields from the text file and it seems as the B) answer will work best.  I will be getting this text file every day and need to add rows to the SQL table but only certain fields.  I have another SQL question pertaining to this but I will open a new question for it.

Thank you again,
r
0
All Courses

From novice to tech pro — start learning today.