T-SQL How to end an IF-ELSE IF-ELSE block
The last ELSE
in your If, ELSE IF, ELSE contains multiple lines of code. You need to start it with BEGIN
and end it with END
. See this MSDN documentation for more details.
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
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
If you want both SELECT -1
and RETURN
to be inside the ELSE
you'll have to use a BEGIN
/ END
block. Now only the SELECT -1
is inside the else branch.
So you need
ELSE
BEGIN
SELECT -1;
RETURN;
END