IF ELSE Control of flow statements — Parv The IT Geek

The IF ELSE statements are one of the most frequently used statement within SQL and control of

flow statements are one of the core statements within any programing language. Once you have

understood the concept you can easily make powerful scripts.

An IF statement is a check to see whether a condition is TRUE and is used in hundreds of different

scenarios such as checking whether an object exists, checking data for a value…… I always liken the

IF statement to checking your fridge for your favourite meal and if its there you eat otherwise you

check out all your other options.

The below is a simple script which tests to see whether I have the AdventureWorks2012 database.

IF EXISTS (SELECT * FROM sys.databases 
WHERE name = 'AdventureWorks2012' )
PRINT 'AdventureWorks2012 is installed'

The result you will get is below.

AdventureWorks2012 is installed

The query checks whether the AdventureWorks2012 returns a value or is TRUE from my query and

then runs the PRINT command to confirm the value was returned as I expected.

You can make the IF statement more powerful by adding the ELSE statement. The ELSE Statement is

used as we often don’t just want to check if a statement is TRUE but also want to produce an action if its false.

DECLARE @TestValue int 
SET @TestValue = 1
IF @TestValue >1
BEGIN
PRINT 'The Test value is greater than 1'
END
ELSE
PRINT 'The Test value is less than or equal to 1'

The result you will get is below.

The Test value is less than or equal to 1


Originally published at https://parvtheitgeek.com on January 14, 2015.

Published by Parvinder Nijjar

I blog at ParvTheITGeek.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

<span>%d</span> bloggers like this: