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.
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.
¶ 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.
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).
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.
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.
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'')'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With