T-SQL command IF is used to control flow of code mainly in operations where we somehow influence db (DDL, DML operations) – for example procedures. You can mix it up with CASE command quite simply. The common mistake is that we try to push sql IF into SELECT clause.
Query in which IF is used in SELECT command will definitely not work (“Incorrect syntax near the keyword IF/THEN”)
SELECT IF 1=1 THEN 'Hi'
IF cannot be inserted into SELECT clause. We use CASE command for this (more in article on CASE)
IF Command Syntax
We start with IF command followed by condition definition. In case when the condition is True command following OF will commence. If not ELSE command will commence.
IF condition
...a statement to be executed if the condition value is TRUE;
ELSE
...a statement to be executed if the condition is FALSE;
This syntax will work but it is more optimal to limit individual commands using BEGIN END clause
IF condition
BEGIN
...a statement to be executed if the condition value is TRUE
END;
ELSE
BEGIN
...a statement to be executed if the condition is FALSE
END;
“THEN” is not used in IF command. Command cannot operate even with ELSEIF. If we would want to test more requirements we would need to branch ot use multiple IFs one after another.