Sql server SqlServer转到退出过程并选择

Sql server SqlServer转到退出过程并选择,sql-server,stored-procedures,Sql Server,Stored Procedures,我知道他们对此有很多决定。 然而如果我有一个过程,那么在很多情况下,我想选择一个结果并退出该过程。 最好使用GOTO语句,或者使用更好的方法(不是经典的if…else) 例如: create procedure MyProc @Parm int as declare @Result nvarchar(50) set @Result = 'OK' if @Parm = 1 begin set @Result = 'Error Example 1'

我知道他们对此有很多决定。 然而如果我有一个过程,那么在很多情况下,我想选择一个结果并退出该过程。 最好使用
GOTO
语句,或者使用更好的方法(不是经典的
if…else

例如:

create procedure MyProc @Parm int
as
    declare @Result nvarchar(50)

    set @Result = 'OK'

    if @Parm = 1 begin
        set @Result = 'Error Example 1'
        goto ExitProc;
    end

    if @Parm = 2 begin
        set @Result = 'Error Example 2'
        goto ExitProc;
    end

    if @Parm = 3 begin
        set @Result = 'Error Example 3'
        goto ExitProc;
    end

    ect...

    ExitProc:

    select @Result as Result, 100 as P2
    from Table1

您可以使用
CASE
而不是
GOTO

CREATE PROCEDURE MyProc @Parm int AS
    DECLARE @Result nvarchar(50)

    SELECT 100 as P2, @Result = CASE @Parm
                         WHEN 1 THEN 'Error Example 1'
                         WHEN 2 THEN 'Error Example 2'
                         WHEN 2 THEN 'Error Example 3'
                         ELSE 'OK'
                     END

你的真实代码比单个if-else-if更复杂吗。。。结构(如注释中所述),然后您可以在需要时引发自己的异常,强制存储过程退出并将错误通知应用程序

例如:

create procedure MyProc @Parm int
as
    if @Parm = 1 begin
        THROW 60001, 'Error Example 1', 1;
    end

    if @Parm = 2 begin
        THROW 60001, 'Error Example 2', 2;
    end

    if @Parm = 3 begin
        THROW 60001, 'Error Example 3', 3;
    end

    ...
现在,您的应用程序可以捕获SQL Server抛出的这些异常,就像它们是任何其他SQL错误一样

您甚至可以在存储过程本身上捕获和处理这些错误,尽管我认为在应用程序上捕获它们更为优雅

捕获存储过程错误的示例:

create procedure MyProc @Parm int
as

    begin try
      if @Parm = 1 begin
        THROW 60001, 'Error Example 1', 1;
      end

      if @Parm = 2 begin
        THROW 60001, 'Error Example 2', 2;
      end

      if @Parm = 3 begin
        THROW 60001, 'Error Example 3', 3;
      end

      ...
    end try

    begin catch
      select error_message() as Result, 100 as P2
      from Table1
    end catch

goto从来都不是一个好的解决方案。关于这一点有很多文章,几十年前就被禁止了。经典的if..else是最好的解决方案,这有什么错?在catch块中,我添加了:“set@@Result=error\u message()”。在每个if块yes中不使用“set@@Result=”…”,这要好得多,因为您还捕获了可能发生的任何其他SQL错误(引用错误,除以0,…),并且您将始终对错误消息()有正确的描述。我将修改答案。这与原始示例不同,在原始示例中,即使parm为1、2或3,也会执行select语句