简体   繁体   English

批量插入跳过最后一行

[英]bulk insert skip last row

I am doing a bulk insert that I have to skip the last row. 我正在执行批量插入,因此必须跳过最后一行。 Otherwise , I got an error saying "Bulk Insert: Unexpected end-of-file (EOF) encountered in data file." 否则,我会收到一条错误消息:“批量插入:数据文件中遇到意外的文件结尾(EOF)”。 If I set ROWTERMINATOR='\\r\\n', then I got 0 rows imported. 如果我设置ROWTERMINATOR ='\\ r \\ n',那么我将导入0行。

I wonder if there is any code that can help me skip the lastrow of the txt file? 我想知道是否有任何代码可以帮助我跳过txt文件的最后一行? (The last row is dynamic.) My company currently doesn't have SSIS installed. (最后一行是动态的。)我的公司当前未安装SSIS。

My code for bulk insert is 我的批量插入代码是

Declare @SQL1 varchar(150), @path varchar(100), 

@pathtable varchar(100), @date datetime

set @date = getdate()


-- set path for files

set @path= 'C:\imp\'

set @pathtable = @path + 'importfile.txt'



delete from IDX

--  set sql

set @SQL1 = "BULK INSERT dbo.table FROM '" + @pathtable 

+ "' WITH (FIRSTROW = 2, MAXERRORS = 0)"


-- Bulk insert

exec(@sql1)

The issue is that the last row contains a row count from the export process. 问题是最后一行包含导出过程中的行数。 If you're able to modify the export process, make sure you use the SQL command: 如果您能够修改导出过程,请确保使用SQL命令:

SET NOCOUNT ON;

If you're using a GUI to export the data there should be a place to modify the T-SQL used or an option to set nocount on. 如果您使用GUI导出数据,则应该有一个地方来修改所使用的T-SQL或一个设置不计数的选项。

This will prevent the last row from writing out to your file. 这样可以防止最后一行写到文件中。

If you cannot modify the export process... You can get crazy and right either a console application to read the data and remove the last line or a CLR that does basically that very task.. Open the file, remove the last line, save the file then call your stored procedure above to bulk insert your data. 如果您无法修改导出过程...您可能会发疯,然后右键单击控制台应用程序以读取数据并删除最后一行,或者执行基本上完成该任务的CLR。.打开文件,删除最后一行,保存然后,该文件将调用上面的存储过程以批量插入数据。

You need to use single quotes ' multiple times, You have used double quotes " which are treated as identifiers in sql server. 您需要多次使用单引号' ,已经使用了双引号" ,在SQL Server中将其视为标识符。

Your query should look like this... 您的查询应如下所示:

Declare @SQL1 varchar(150)
      , @path varchar(100)
      , @pathtable varchar(100)
      , @date datetime

SET @date = getdate();

SET @path= 'C:\imp\'
SET @pathtable = @path + 'importfile.txt'


SET @SQL1 = 'BULK INSERT dbo.table 
             FROM ''' + @pathtable + ''' 
             WITH ( 
                     FIRSTROW  = 2
                   , MAXERRORS = 0
                   )';

Now if you print this SQL statement it would look like this... 现在,如果您打印此SQL语句,它将看起来像这样...

PRINT @SQL1

RESULT:

BULK INSERT dbo.table 
             FROM 'C:\imp\importfile.txt' 
             WITH ( 
                     FIRSTROW  = 2
                   , MAXERRORS = 0
                   )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM