We help IT Professionals succeed at work.

SQL SERVER SCRIPT - NESTED IF STATEMENTS

I am attempting to figure out a SQL script and am unclear how nested IF statements behave. An example of what I am trying to figure out is shown below. Assuming that the 1st IF statement is true (A='22222'), does the last IF statement (IF D = 'ORTGNV')  get evaluated regardless of the answer to the second IF statement (IF B='12345' and C='98765')? I've also attached a word copy of the script in case indentation is messed up.

IF A = ‘22222’
      BEGIN
            DO AAA
            IF B = ‘12345’ and C = ‘98765’
                  BEGIN
                        DO BBB
                  END
            ELSE
                  BEGIN
                        DO CCC
                  END
            IF D = ‘ORTGNV’
                  BEGIN
                        DO DDD
                  END
END
SQL-Script-Nested-IF.docx
Comment
Watch Question

IT Engineer
Distinguished Expert 2017
Commented:
Yes, the last IF will be evaluated no matter the values of B and C are. It only depends on A value (‘22222’).
Jim HornSQL Server Data Dude
Most Valuable Expert 2013
Author of the Year 2015
Commented:
>Assuming that the 1st IF statement is true (A='22222'), does the last IF statement (IF D = 'ORTGNV')  get evaluated regardless of the answer to the second IF statement (IF B='12345' and C='98765')?

Yes, as the first IF has a BEGIN..END block that includes the IF D test, and the IF B..C block has that IF with an ELSE, so either way code execution will continue down to the IF D line.

And in case you're wondering, IF statements only execute the very next line, and the way to get around that is to enclose multiple lines in an begin..end block.   So the begin's and end's involving b,c and d are really not necessary as they are executing only a single line.
Pawan KumarDatabase Expert
Awarded 2016
Top Expert 2016
Commented:
IF D = ‘ORTGNV’ is executed IF A = ‘22222’.
IF A <> ‘22222’ Then nothing inside if is executed.
IF B = ‘12345’ and C = ‘98765’ THEN its begin part is executed.
IF NOT ( B = ‘12345’ and C = ‘98765’ ) Then its else part is executed.

Author

Commented:
Thank you very much for your timely help.