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
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.
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.
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 (?)
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With