Wednesday, April 13, 2011

SQL-IF and CASE

This time around am going to take a look into the 'if' and 'case' used in SQL... as you can see in the code given below you have a very good feature from SQL. Making decisions inside a query can come in very handy as show below in the given 'if' statements included in this query.

DECLARE @num int
SET @num = 4

DECLARE @salesPersonId int

if @num = 3
BEGIN
 set @salesPersonId = 
 (
  SELECT top 1 SalesPersonID
  FROM Sales.SalesPerson
 )
 SELECT 'The number is 3' [Output]
END
ELSE IF @num = 4
BEGIN
 set @salesPersonId = 4
 SELECT 'The number is 4' [Output]
END
ELSE
BEGIN
 set @salesPersonId = -1
 SELECT 'The number is not valid' [Output]
END


IF @salesPersonId = -1
BEGIN
 SELECT 'No Sales Person selected' SalesPersonId
END
ELSE
BEGIN
 SELECT @salesPersonId SalesPersonId
END

Below this paragraph is a code snippet with a 'case' used to set the 'EmailPromotion' to a more user friendly look, it is actually given as an 'int', by taking in the EmailPromotion and setting it to a string that better ids the kind of promotion that the person is asking for.

SELECT FirstName, LastName,
(
 CASE EmailPromotion
  WHEN 1 THEN 'EmailPromo'
  WHEN 2 THEN 'TextPromo'
  ELSE 'NadaPromo'
 END
) Promo
FROM Person.Contact c

More to Come, CA.

No comments:

Post a Comment