错误没有从BULK INSERT IN try块中引发

时间:2017-11-13 12:53:22

标签: sql-server tsql bulkinsert

嗨我已经在try块中写了下面的代码但是没有引发错误来捕获块。但独立的批量插入生成错误消息。

BEGIN TRY

SET @sql = 
                '
                    BULK INSERT dbo.vw_Data_Import_ISO_CSP_OPMHC_Premium--<-- table view
                    FROM ''' + @SourceFilePath + '''
                    WITH ( FIRSTROW = 2, FIELDTERMINATOR = ''|'', ROWTERMINATOR = ''\n'' );
                '

EXECUTE (@sql)

END TRY
BEGIN CATCH

        SELECT 
            @error_number = ERROR_NUMBER(), 
            @error_message = ERROR_MESSAGE(), 
            @error_line = ERROR_LINE()
        SELECT @error_description = 'T-SQL error number ' + CAST(@error_number AS VARCHAR(10))  + ' on line ' + CAST(@error_line AS VARCHAR(10)) + '.'

END CATCH 

1 个答案:

答案 0 :(得分:0)

您没有在CATCH块中引发错误,只是分配变量值。尝试添加RAISERROR

BEGIN TRY
    SET @sql = ' BULK INSERT dbo.vw_Data_Import_ISO_CSP_OPMHC_Premium --<-- table view 
FROM ''' + @SourceFilePath + ''' WITH ( FIRSTROW = 2, FIELDTERMINATOR = ''|'', ROWTERMINATOR = ''\n'', MAXERRORS = 0 );'
    EXECUTE (@sql);
END TRY BEGIN CATCH
    SELECT 
        @error_number = ERROR_NUMBER(), 
        @error_message = ERROR_MESSAGE(), 
        @error_line = ERROR_LINE();
    SELECT @error_description = 'T-SQL error number ' + CAST(@error_number AS VARCHAR(10))  + ' on line ' + CAST(@error_line AS VARCHAR(10)) + '.';
    RAISERROR(@error_description, 16, 1);
END CATCH; 

在SQL Server 2012及更高版本中,可以使用THROW简化CATCH块:

BEGIN CATCH
    IF @@TRANCOUNT > 0 ROLLBACK;
    THROW;
END CATCH;