为什么在以下代码中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.
答案 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'')'