【问题标题】:sybase alternative way for @@error to catch error@@error 捕获错误的 sybase 替代方法
【发布时间】:2016-01-26 16:51:23
【问题描述】:

通常我会遇到这样的错误

EXECUTE (@STATEMENT)

SELECT @ERR_CODE = @@ERROR

它处理简单的错误,例如下面的查询.. @@ERROR 返回值

 insert into tab1 values(1) -- error attempt to insert unique constraint

但是下面的查询也给出了唯一约束错误但是@ERROR 没有捕捉到它返回空值

insert into tab1 select id from tab2 

所以上面的语句给出了唯一的约束但是@ERROR 没有捕捉到它

另一个例子我有以下错误

sybase could not acquire a lock within the specified wait period

@ERROR 也没有捕获

我的问题是有一种方法可以在执行语句时捕获任何错误?

【问题讨论】:

  • @MichaelGardner 在你的回答中解释了如何设置错误但是我的问题是为什么@@error 没有返回错误,还有其他方法吗?
  • 我不确定。我只知道在我们的应用程序中,我们会定义大量自定义错误,并在执行期间测试/抛出这些错误。根据我记得在 SO 上看到的其他问题,捕获所有错误似乎很棘手。不幸的是,我不是开发人员,所以我不知道其中的细节。
  • @MichaelGardner 好吧,uniqueconstraint 错误非常简单,但是如果我用 insert.. select 尝试它就不会发现它。如果我开始设置消息,它会有点复杂,虽然我会考虑它。
  • @MichaelGardner 我希望他能找到一个窍门。感谢您对迈克尔的支持

标签: sybase


【解决方案1】:

您确定在插入约束失败和查看@@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

 -----------
        2601

【讨论】:

  • 感谢您的回答,我会写下关于我的问题的完整示例,以便您查看。
  • 使用“with ignore_dup_key”子句创建索引。
猜你喜欢
  • 1970-01-01
  • 2022-12-02
  • 2010-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多