SQL Server 未从BULK INSERT IN try块引发错误

yzuktlbb  于 2022-12-22  发布在  其他
关注(0)|答案(1)|浏览(106)

嗨,我已经在try块中写了下面的代码,但是没有向catch块提交错误。但是独立的批量插入生成错误消息。

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
xmakbtuz

xmakbtuz1#

您没有在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;
    • 编辑:**

正如注解中所建议的,在源中的某些记录无法解析并且可能被跳过的情况下,非零MAXERRORS规范非常有用。

相关问题