Bulk insert .txt file in SQL

自作多情 提交于 2019-12-02 04:36:37

问题


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:


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'
    );


来源:https://stackoverflow.com/questions/30868771/bulk-insert-txt-file-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!