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

前端 未结 6 1666
野的像风
野的像风 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-12 11:19

    In your example, RETURN always runs.

    From a coding practice standard, you should always use BEGIN and END in SQL in my opinion to clearly state what is intended to be in the logical block. I prefer the same pattern in C# where I use braces even when not needed. The indentation is important in my opinion as well as it easily lets you track where it starts and finishes.

    IF(1=2)
       BEGIN
          SELECT 1
       END
    SELECT 2
    
    IF(1=2) SELECT 1
       SELECT 2
    

    These are equivalent in behavior, but the first clearly shows SELECT 1 is dependent on the logical condition above it.

    What you really want is:

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

提交回复
热议问题