• 13. 1. 2020
  • Ing. Jan Zedníček - Data Engineer & Controlling
  • 0

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'

SQL IF

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.

Rate this post

Ing. Jan Zedníček - Data Engineer & Controlling

My name is Jan Zedníček and I have been working as a freelancer for many companies for more than 10 years. I used to work as a financial controller, analyst and manager at many different companies in field of banking and manufacturing. When I am not at work, I like playing volleyball, chess, doing a workout in the gym.

🔥 If you found this article helpful, please share it or mention me on your website

Leave a Reply

Your email address will not be published. Required fields are marked *