Frequently used in Stored Procedures, the SQL If can be used to help control the flow and execution of your SQL.
The If checks to see if a boolean statement is true, and if it is, the code directly beneath is executed. This is handy, as we often need to execute completely different code depending on the value of a variable.
The syntax is easy to use, but can make a big difference to your code:
SELECT @Value = COUNT(*) FROM SpecialOffers WHERE Valid = 1
IF (@Value > 0)
BEGIN
SELECT * FROM SpecialOffersProducts
END
ELSE
SELECT * FROM Products
The above code is counting the number of valid special offers and assigning the number to the variable @Value.
The If then checks that @Value is greater than zero, meaning there are valid special offers available. If the check is true, and there are special offers available, our SpecialOffersProducts will be returned. If the count returns as zero, the else will be executed, and the Products will be returned.
The above example would typically be used within a stored procedure
Multiple conditions can be specified within the If with the use of the AND and OR keywords.