Problem: How to exit from a
query without executing the rest of the code.
Exits unconditionally from a query or
procedure. RETURN is immediate and complete and can be used at any point to
exit from a procedure, batch, or statement block. Statements that follow RETURN
are not executed.
Example:
In this
article I am going to show you how return can be used and a few examples.
Let’s see how we can change the below code to exit using a
return command.
Declare @counter int =4
SELECT
@Counter
IF @Counter
= 4 GOTO
Branch_One --Jumps to the first branch.
IF @Counter
= 5 GOTO
Branch_Two --Jumps
to the Second Branch.
Branch_One:
SELECT 'Jumping To Branch One.';
Branch_Two:
SELECT 'Jumping To Branch Two.' ;
Branch_Three:
SELECT 'Jumping To Branch Three.';
After adding return to the code and see how it can help to
break after the first return.
Declare @counter int =4
SELECT
@Counter
IF
@counter NOT IN (4,5) RETURN;
IF @Counter
= 4 GOTO
Branch_One --Jumps to the first branch.
IF @Counter
= 5 GOTO
Branch_Two --Jumps to the Second Branch.
Branch_One:
SELECT 'Jumping To Branch One.';
RETURN
Branch_Two:
SELECT 'Jumping To Branch Two.' ;
RETURN
Branch_Three:
SELECT 'Jumping To Branch Three.';
RETURN
OUTPUT:
interesting concept
ReplyDeleteinteresting concept
ReplyDelete