Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TRY doesn't CATCH error in BULK INSERT

Why in the following code TRY didn't catch the error and how can I catch this error?

BEGIN TRY
  BULK INSERT [dbo].[tblABC]
  FROM 'C:\temp.txt'
  WITH (DATAFILETYPE = 'widechar',FIELDTERMINATOR = ';',ROWTERMINATOR = '\n')
END TRY

BEGIN CATCH
  select error_message()
END CATCH

I just get this:

Msg 4860, Level 16, State 1, Line 2
Cannot bulk load. The file "C:\temp.txt" does not exist.
like image 500
hoggar Avatar asked Mar 16 '14 22:03

hoggar


People also ask

How do you handle errors in bulk insert in mule 4?

It may happen that while some statements in the bulk operation can be successfully executed, some may result in an error. When this occurs, it will be up to the driver to either: Stop execution immediately and ignore all remaining operations, or. Continue to execute the remaining statements.

Why bulk insert is faster than insert?

¶ Both 'Bulk insert with batch size' and 'Use single record insert' options are used for inserting records in a database table. The 'Bulk insert with batch size' option is used when you want the whole dataset to be loaded in batches of a specified size. Typically, larger batch sizes result in better transfer speeds.

What does the bulk insert command do?

BULK INSERT loads data from a data file into a table. This functionality is similar to that provided by the in option of the bcp command; however, the data file is read by the SQL Server process. For a description of the BULK INSERT syntax, see BULK INSERT (Transact-SQL).

How can I speed up bulk insert in SQL?

Below are some good ways to improve BULK INSERT operations : Using TABLOCK as query hint. Dropping Indexes during Bulk Load operation and then once it is completed then recreating them. Changing the Recovery model of database to be BULK_LOGGED during the load operation.


2 Answers

This is one option that helps to catch this error:

BEGIN TRY
 DECLARE @cmd varchar(1000)
 SET @cmd = 'BULK INSERT [dbo].[tblABC] 
  FROM ''C:\temp.txt'' 
  WITH (DATAFILETYPE = ''widechar'',FIELDTERMINATOR = '';'',ROWTERMINATOR = ''\n'')'
 EXECUTE (@cmd)
END TRY

BEGIN CATCH
 select error_message()
END CATCH

After this I got the following error in CATCH:

Cannot bulk load. The file "C:\temp.txt" does not exist.
like image 86
hoggar Avatar answered Sep 26 '22 02:09

hoggar


You should add MAXERRORS parameter as zero, the default value is 10:

SET @cmd = 'BULK INSERT [dbo].[tblABC] 
  FROM ''C:\temp.txt'' 
WITH (MAXERRORS = 0, DATAFILETYPE = ''widechar'',FIELDTERMINATOR = '';'',ROWTERMINATOR = ''\n'')'
like image 24
JohnJames Avatar answered Sep 26 '22 02:09

JohnJames