【问题标题】:Error Handling in SybaseSybase 中的错误处理
【发布时间】:2012-09-30 07:18:42
【问题描述】:

有没有办法处理SYBASE 中的错误,例如可以在MS SQL ServerOracle 等中使用的TRY-CATCH 块?

我在网上搜索过,我找到的唯一选项是全局变量@@error,但它并没有像我预期的那样工作,例如,以下代码:

begin tran

update table1
set name = 'new name'
where name = 'old name'

update table2
set id = 1 
where id = 30
-- suppose id has a unique constraint and there's already a row with id = 1

IF @@error = 0
begin
    print 'commited'
    commit
end
else
begin
    print 'rolled back'
    rollback
end

确实会以某种方式回滚,因为我在 table1 上更改的名称保留了我在这里测试过的旧值,但它不会打印消息,也不会执行我在导致错误

任何人都可以帮助我吗?您知道 Sybase 错误处理的实际工作原理吗?

【问题讨论】:

  • 您可以在更新中设置一个 if 块,这样就不会出现错误。 if(not exists(select 1 from table2 where id = 1))begin/* 你的更新代码在这里*/end
  • 感谢您的回复,但我需要在脚本中执行类似的操作,该脚本将执行大量插入/更新,并且可能会违反很多约束,因此验证将花费大量时间的代码。另外,如果没有这些验证,脚本已经有超过 1200 行代码,所以 try-catch 块或类似的东西会更合适,但似乎不可能,所以我正在考虑让 sybase 回滚交易本身发生错误。
  • 尝试查看允许您定义自己的错误消息的 'sp_addmessage' 命令,以及允许您定义错​​误消息的 'raiserror' 命令你调用这些错误,并设置@@error 的值。
  • 在我关于 sybase-iq 的文档中,我读到有一个 exception 语句。具有 catch 块的功能。

标签: sql try-catch sybase


【解决方案1】:

第一种解决方案。

您无法在 Sybase 上以这种方式捕获异常。在更新之前,您必须检查数据:

if not exists
(
  select 1 from table2
  where id = 1
)
begin
  update table2
  set id = 1 
  where id = 30
end
else
begin
  print 'rolled back'
  rollback
end

第二个解决方案。

您也可以将更新命令放入过程中,然后您可以捕获异常。 创建过程:

create procedure myproc
as
begin
  update table2
  set id = 1 
  where id = 30
end

然后运行如下:

begin tran

update table1
set name = 'new name'
where name = 'old name'

exec myproc

IF @@error = 0
begin
    print 'commited'
    commit
end
else
begin
    print 'rolled back'
    rollback
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-18
    • 2015-07-09
    • 2013-08-08
    • 1970-01-01
    • 1970-01-01
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多