Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 DML statements as part of the ELSE block.

SQL Server 2014

How do I end an IF-ELSE-ELSE-IF block?

ALTER PROCEDURE [GenerateNumber] (     @Code VARCHAR(2) ) AS BEGIN     DECLARE @stringConcat VARCHAR = 'X';      IF @Code = 'KP'         SET @stringConcat += 'Y';     ELSE IF @Code = 'RL'         SET @stringConcat += 'Z';     ElSE         -- Return error code and stop processing         SELECT -1;         RETURN;      BEGIN TRY         -- Various DML statements...          SELECT @successValue;         RETURN;     END TRY     BEGIN CATCH         SELECT -1;         RETURN;     END CATCH END 
like image 940
contactmatt Avatar asked Sep 16 '15 17:09

contactmatt


People also ask

Does SQL have Elseif?

Any T-SQL statement can be executed conditionally using IF… ELSE. If the condition evaluates to True, then T-SQL statements followed by IF condition in SQL server will be executed. If the condition evaluates to False, then T-SQL statements followed by ELSE keyword will be executed.

Is != Or <> better in SQL?

If != and <> both are the same, which one should be used in SQL queries? Here is the answer – You can use either != or <> both in your queries as both technically same but I prefer to use <> as that is SQL-92 standard.

What does like %% mean in SQL?

The LIKE command is used in a WHERE clause to search for a specified pattern in a column. You can use two wildcards with LIKE : % - Represents zero, one, or multiple characters. _ - Represents a single character (MS Access uses a question mark (?)


2 Answers

Okay you have to use Begin and End in the Else statement as it contains multiple lines of code.

    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 
like image 125
Krishnraj Rana Avatar answered Sep 23 '22 08:09

Krishnraj Rana


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 
like image 29
Brian Stork Avatar answered Sep 22 '22 08:09

Brian Stork