一旦违反条件,就停止执行存储过程。?

问题描述 投票:0回答:2

我有以下存储过程,并且一旦事实表中的行数与历史数据不同,我想中止该存储过程。所以我正在尝试做类似的事情,直到现在它仅向用户发送数据不相同的电子邮件,但是我想添加另一个功能,即,如果行差异大于5,则中止/停止SP %。但是它不能正常工作。谁能解释我在哪里犯错了?以下是我要进行修改的存储过程的一部分:

SET XACT_ABORT ON;

Begin Try

    Begin Transaction;

    if (@delta_ok = 0)

        set @email_body = @email_body+char(13)+char(10)+'ETL process has been stopped.'

    Return

    else

        set @email_body = @email_body+char(13)+char(10)+'ETL process is copying the data .'

    Commit Transaction;

    Begin Catch

        Rollback Transaction

    End Catch

End Try

因此,我的问题是,如果将“ RETURN”放入“ if”语句中,它将停止SP?一旦违反条件?如果不满足条件,则传递给“ ELSE”?

sql sql-server stored-procedures abort
2个回答
0
投票

所以我设法按照其他用户的建议进行了更改。

SET XACT_ABORT ON;
Begin 
 Begin Try
  Begin Transaction;

  if (@delta_ok = 0)
  set @email_body = @email_body+char(13)+char(10)+'ETL process has been stopped.'
  Return
  else
  set @email_body = @email_body+char(13)+char(10)+'ETL process is copying the data .'
  Commit Transaction;
 End Try
 Begin Catch
  Rollback Transaction
 End Catch

End

0
投票

您的语法在这里到处都是。使用某种格式来增加清晰度将有很大帮助。您的代码中也有一个反模式,我称之为Try / Squelch。您发现了一个错误,但是随后吞下了它,并且不告诉任何人它发生了。发生异常时,您需要处理它们。这意味着您需要告诉调用程序出了什么问题,而不仅仅是默默地接收细节,这样没人知道它发生了或如何修复。

Begin Try
    Begin Transaction;

    if (@delta_ok = 0)
        begin
            set @email_body = @email_body + char(13) + char(10) + 'ETL process has been stopped.'
            Return
        end
    else
        begin
            set @email_body = @email_body + char(13) + char(10) + 'ETL process is copying the data .'
            Commit Transaction;
        end
End Try

Begin Catch
    Rollback Transaction
    --you really need something here to log/audit and probably tell the calling program something failed.
End Catch
© www.soinside.com 2019 - 2024. All rights reserved.