Monday, June 4, 2012

SQL Case Statement


CASE Statement example

SELECT
'Title' =
CASE TITLEOFCOURTESY
WHEN 'MS.' THEN 'MISSUS'
WHEN 'MRS.' THEN 'MISTRESS'
WHEN 'MR.' THEN 'MISTER'
WHEN 'DR.' THEN 'DOCTOR'
ELSE ''
END,
TITLEOFCOURTESY,
FIRSTNAME,
LASTNAME
FROM EMPLOYEES 
Output:
Title TitleOfCourtsey FirstName LastName
Missus Ms. Nancy Davolio
Doctor Dr. Andrew Fuller
Missus Ms. Janet Leverling

Example when the case input and output column is same, then use below query


SELECT PartId,

CASE Partcode WHEN 'AM102' THEN '1'
ELSE 'NULL'
END Code,
CtNumber FROM MySource.dbo.Inventory 

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.