在BULK INSERT中TRY没有CATCH错误

时间:2014-03-16 22:52:49

标签: tsql error-handling try-catch bulkinsert

为什么在以下代码中TRY没有捕获到错误,如何捕获此错误?

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

我得到这个:

Msg 4860, Level 16, State 1, Line 2
Cannot bulk load. The file "C:\temp.txt" does not exist.

2 个答案:

答案 0 :(得分:7)

这是一个有助于捕获此错误的选项:

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

在此之后我在CATCH中收到以下错误:

Cannot bulk load. The file "C:\temp.txt" does not exist.

答案 1 :(得分:2)

您应将 MAXERRORS 参数添加为零,默认值为10:

SET @cmd = 'BULK INSERT [dbo].[tblABC] 
  FROM ''C:\temp.txt'' 
WITH (MAXERRORS = 0, DATAFILETYPE = ''widechar'',FIELDTERMINATOR = '';'',ROWTERMINATOR = ''\n'')'