Bulk insert .txt file in SQL

4.8k views Asked by At

I'm trying to import a .txt file into Advanced Query Tool (the SQL client I use). So far, I have:

CREATE TABLE #tb_test
(
id INTEGER,
name varchar(10),
dob date,
city char(20),
state char(20),
zip integer
);

insert into #tb_test
values
(1,'TEST','2015-01-01','TEST','TEST',11111)
;

bulk insert #tb_test
from 'h:\tbdata.txt'
    with
    (
    fieldterminator = '\t',
    rowterminator = '\n'
    );

I receive an error message saying there's a syntax error on line 1. Am I missing a database from which #tb_test comes (like db.#tb_test)?

Here's a line from the tbdata.txt file:

2,'TEST2','2012-01-01','TEST','TEST',21111
1

There are 1 answers

2
Pimenta On

I was curious with this question and I found the following solution:

Your data is comma separated but you are trying to split by TAB two options: change the file data to be TAB separated or change the fieldterminator = '\t' to fieldterminator = ','

The DATE format has issues when loading directly from a file, my best solution is to change the temp field dob to type VARCHAR(20) and then, when passing to the final display/data storage convert to DATE.

Here is the corrected code:

CREATE TABLE #tb_test
(
id INTEGER,
name varchar(10),
dob varchar(20),
city char(20),
state char(20),
zip integer
);

insert into #tb_test
values
(1,'TEST','2015-01-01','TEST','TEST',11111)
;

bulk insert #tb_test
from 'h:\tbdata.txt'
    with
    (
    fieldterminator = ',',
    rowterminator = '\n'
    );