通常,我会像这样捕获错误
EXECUTE (@STATEMENT)
SELECT @ERR_CODE = @@ERROR它处理简单的错误,如下面的查询。@@ERROR返回值
insert into tab1 values(1) -- error attempt to insert unique constraint然而,下面的查询也给出了unique约束错误,但是@ERROR没有捕捉到它,它返回空值
insert into tab1 select id from tab2 所以上面语句给出了唯一的约束,但是@ERROR没有捕捉到它
另一个例子我有下面的错误
sybase could not acquire a lock within the specified wait period@ERROR也没有捕获到
我的问题是,有什么方法可以在执行语句时捕捉到任何错误吗?
发布于 2016-01-26 16:51:23
您绝对确定在insert出现约束失败和查看@@error之间没有语句吗?任何东西都会重置@@error。
这并不是因为您在EXECUTE()中使用了动态SQL -- @@error仍然是可用的。
试着和下面的我做同样的事情--你会变得不同吗?
create table tempdb..abe(a int)
select 1 a into #a
insert #a values (1)
create unique index x on tempdb..abe(a)
insert tempdb..abe select * from #a
Msg 2601, Level 14, State 2:
Server 'CRENG_QA', Line 1:
Attempt to insert duplicate key row in object 'abe' with unique index 'x'
Command has been aborted.
(0 rows affected)
select @@error
-----------
2601
execute('insert tempdb..abe select * from #a')
Msg 2601, Level 14, State 2:
Server 'CRENG_QA', Line 1:
Attempt to insert duplicate key row in object 'abe' with unique index 'x'
Command has been aborted.
(0 rows affected)
select @@error
-----------
2601https://stackoverflow.com/questions/34995600
复制相似问题