SQL try-catch语句不处理错误(SQL Server 2008)

Cha*_*ams 4 sql error-handling try-catch sql-server-2008

我试图使用try-catch在SQL查询(而不是在存储过程中)中捕获错误.

由于某种原因,这不是处理我的错误,我仍然得到:

消息213,级别16,状态1,行29列名称或提供的值的数量与表定义不匹配.

有什么帮助吗?

begin try
create table #temp_hierarchy
    (temp_gl_number varchar(50)
    ,temp_store_location varchar(255)
    ,temp_store_key varchar(50)
    ,temp_serving_dc varchar(50)
    ,temp_exploris_db varchar(50)
    ,temp_dc_account varchar(50)
    ,temp_store_type varchar(50)
    ,temp_dvp_ops varchar(50)
    ,temp_rdo varchar(50)
    ,temp_team varchar(50)
    ,temp_dvp_sales varchar(50)
    ,temp_rds varchar(50)
    ,temp_closed varchar(50)
    ,temp_open_date varchar(50)
    ,temp_close_date varchar(50)
    ,temp_store_manager varchar(250)
    ,temp_sales_teammate varchar(250)
    ,temp_machine_shop varchar(50)
    ,temp_address varchar(250)
    ,temp_city varchar(50)
    ,temp_state varchar(50)
    ,temp_zip varchar(50)
    ,temp_phone varchar(50)
    ,temp_fax varchar(50))

insert into #temp_hierarchy
select * 
from OPENROWSET('Microsoft.ACE.OLEDB.12.0', 
    'Excel 12.0;Database=C:\SQL_DATA_REPORTING\8-31-11 Store Hierarchy.xlsx;HDR=YES', 
    'SELECT * FROM [Master List$]');

truncate table tbl_hierarchy

insert into tbl_hierarchy
select *
from #temp_hierarchy
where temp_gl_number is not null
    and temp_gl_number <> 'GLID'

select @@ROWCOUNT + ' Records sucessfully imported'

end try

begin catch
select 'ERROR: ' & ERROR_NUMBER() + '. Unable to import records, existing data was not lost.' 
end catch;
go
Run Code Online (Sandbox Code Playgroud)

etl*_*ens 12

您有一个编译时错误,无法在try-catch中捕获.

BooksOnline:

编译和语句级重新编译错误

如果错误发生在与TRY ... CATCH构造相同的执行级别,则TRY ... CATCH将无法处理两种类型的错误:

  1. 编译错误,例如阻止批处理执行的语法错误.

  2. 语句级重新编译期间发生的错误,例如由于延迟名称解析而在编译后发生的对象名称解析错误.

  • 那讲得通。那我怎么能捕获这个错误呢? (2认同)
  • @ChandlerPelhams在该BOL文章中进一步说明它使用动态sql或在存储过程中包装查询.try-catch将抓住它. (2认同)