IT:AD:SQL Server:HowTo:SQL:Functions/Flow Control
##Summary ##
Flow control in stored procs and functions is generally done with IF/ELSE or CASE, clumsy syntax as they are.
Notes
Below are some examples of each type of flow control.
IF/ELSE
Simpler/than/CASE/WHEN/etc, the syntax is just IF (condition) … ELSE … :
DECLARE @compareprice money, @cost money
EXECUTE Production.uspGetList '%Bikes%', 700,
@compareprice OUT,
@cost OUTPUT
IF @cost <= @compareprice
BEGIN
PRINT 'Something'
END
ELSE
-- No wrapping with Begin/End required if only one one line:
PRINT 'Something else'
BEGIN/END statements can be nested1).
Inline Flow
That said, most times, people are simply looking for:
ISNull(sum(Amount),0)
And no…there is no IIF… or ternary ? statement in SQL Server (in 2010). Use CASE.
Case Switching
For more complex branching, use CASE:
CASE Committee WHEN 'Foo' THEN 'Y' WHEN 'Bar' THEN 'Y' ELSE '' END As Committee
Goto
GOTO You can use GOTO statements to jump around if you want:
--Define the label: label : --Alter the execution: GOTO label