T-SQL How to end an IF-ELSE IF-ELSE block

前端 未结 6 1742
野的像风
野的像风 2021-02-12 10:44

When I run the below procedure with the correct parameters so that the -1 value isn\'t returned, none of my DML statements are firing. I\'m guessing that it\'s treating all my D

6条回答
  •  天命终不由人
    2021-02-12 11:12

    Your indenting is lying to you.

    IF @Code = 'KP'
         SET @stringConcat += 'Y';
     ELSE IF @Code = 'RL'
         SET @stringConcat += 'Z';
     ElSE
         -- Return error code and stop processing
         SELECT -1;  -- THIS is evaluated as the ELSE
         RETURN;     -- THIS is run regardless.
    

    Only the 1st line after that last ELSE will be executed as an ELSE condidion. That RETURN will be run regardless. Your BEGIN TRY can't be reached.

    Try this:

    IF @Code = 'KP'
         SET @stringConcat += 'Y';
     ELSE IF @Code = 'RL'
         SET @stringConcat += 'Z';
     ElSE
         BEGIN
         -- Return error code and stop processing
         SELECT -1;
         RETURN;
         END
    

提交回复
热议问题