RSS Feed

SQL Case Expression

SQL Case Expression

Because the case expression returns an expression, it may be used anywhere in the SQL DML statement (Select, Insert, Update, Delete) where an expression may be used, including column expressions, Join conditions, Where conditions, Having conditions or int the order by. [SQL Server 2005 Bible By Paul Nielsen]

Example 1 of SQL Case Expression

[First query is shown just for reference]
Select * From Employees
  
SELECT CASE
  WHEN TitleOfCourtesy IN('Mr.','Sr.','Sra.') THEN 'Male'
  WHEN TitleOfCourtesy IN('Mrs.','Ms.','Ms') THEN 'Female'
  ELSE 'N/A'
  END AS TitleOfCourtesy
  , FirstName , LastName
FROM Employees

Example 2 of SQL Case Expression

[First query is shown just for reference]
Select * From Employees
  
SELECT CASE
  WHEN Country = 'USA' Then 'Western'
  WHEN Country = 'UK' Then 'London'
  ELSE 'Globe'
  END 
  , FirstName , LastName
FROM Employees

No comments:

Post a Comment