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.

Below are some examples of each type of flow control.

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).

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.

For more complex branching, use CASE:

CASE Committee 
WHEN 'Foo' THEN 'Y'
WHEN 'Bar' THEN 'Y'
ELSE ''
END As Committee

GOTO You can use GOTO statements to jump around if you want:

--Define the label: 
label : 

--Alter the execution:
GOTO label


  • /home/skysigal/public_html/data/pages/it/ad/sql_server/howto/sql/functions_flow_control.txt
  • Last modified: 2023/11/04 02:28
  • by 127.0.0.1