You are on page 1of 13

To find out whether a condition is true, you use the IF operator of Transact-SQL.

Its basic formula is: IF Condition Statement When creating an IF statement, first make sure you provide a Condition expression that can be evaluated to produce true or false. To create thisCondition, you can use variables and the logical comparison operator reviewed above.

When the interpreter executes this statement, it first examines the Condition to evaluate it to a true result. If the Condition produces true, then the interpreter executes the Statement. Here is an example: DECLARE @DateHired As datetime2, @CurrentDate As datetime2 SET @DateHired = N'1996/10/04' SET @CurrentDate = N'2007/04/11' IF @DateHired < @CurrentDate PRINT N'You have the experience required for a new promotion in this job' GO

The IF condition we used above is appropriate when you only need to know if an expression is true. There is nothing to do in other alternatives. Consider the following code: DECLARE @DateHired As datetime2, @CurrentDate As datetime2 SET @DateHired = N'1996/10/04' SET @CurrentDate = N'2007/04/16' IF @DateHired > @CurrentDate PRINT N'You have the experience required for a new promotion' GO

Notice that, in case the expression to examine produces a false result, there is nothing to do. Sometimes this will happen.

The CASE keyword is used as a conditional operator that considers a value, examines it, and acts on an option depending on the value. The formula of the CASE statement is: CASE Expression WHEN Value1 THEN Result WHEN Value2 THEN Result WHEN Value_n THEN Result END

In most cases, you may know the only types of value that would be submitted to a CASEstatement. In some other cases, an unpredictable value may be submitted. If you anticipate a value other than those you are aware of, the CASE statement provides a "fitall' alternative by using the last statement as ELSE. In this case, the formula of the CASE statement would be: CASE Expression WHEN Value1 THEN Result WHEN Value2 THEN Result WHEN Value_n THEN Result END ELSE Alternative

This means that it is a valuable safeguard to always include an ELSE sub-statement in a CASEstatement.

You might also like