BULK INSERT missing last row?

五迷三道 提交于 2019-12-05 19:03:06

I reproduced your issue on SQL Server 2008 R2. The solution is as simple as adding a newline to your file so that the last row terminates with a newline.

I created two files:

Then ran the following script:

CREATE TABLE #t(first_name VARCHAR(128),last_name_etc VARCHAR(128),sex CHAR(1),test VARCHAR(128));

BULK INSERT #t
FROM 'C:\temp\without_newline.txt'
WITH (
    FIELDTERMINATOR='\t',
    ROWTERMINATOR='\n'
);

SELECT * FROM #t;

TRUNCATE TABLE #t;

BULK INSERT #t
FROM 'C:\temp\with_newline.txt'
WITH (
    FIELDTERMINATOR='\t',
    ROWTERMINATOR='\n'
);

SELECT * FROM #t;

DROP TABLE #t;

Result 1:

first_name  | last_name_etc     | sex | test
--------------------------------------------
Tom         | Jackson 2/28/1986 | M   | test

Result 2:

first_name  | last_name_etc     | sex | test
--------------------------------------------
Tom         | Jackson 2/28/1986 | M   | test
Mike        | Johnson 1/29/1987 | M   | NULL

The solution should be as simple as making sure the last line terminates with \r\n. Either you change the process that generates the text file or do it manually right before you do the bulk insert.

One way to do this manually would be to run EXEC xp_cmdshell 'echo. >> C:\temp\without_newline.txt' right before you do the bulk insert.

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