• 13. 1. 2020
  • Ing. Jan Zedníček - Data & Finance
  • 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”)



(!!!) 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;

   ...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
     ...a statement to be executed if the condition value is TRUE
     ...a statement to be executed if the condition is FALSE

(!!!) “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 & Finance

My name is Jan Zedníček and I work as a freelancer. 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 and I enjoy tasting of best quality rums.
I am trying to summarize all my knowledge on this website not to forget them and to put them forward to anyone.

Leave a Reply

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