The case for CASEBy Bill Graziano on 6 October 2000 | Tags: SELECT We get many questions asking whether it's possible to use an IF clause inside a SELECT statement. Well, not exactly. But you can use CASE to do the exact same thing. CASE comes in two basic formats, simple and searched. Let's start with an example of what a simple CASE statement in a query looks like: SELECT au_fname, au_lname, CASE state WHEN 'CA' THEN 'California' WHEN 'KS' THEN 'Kansas' WHEN 'TN' THEN 'Tennessee' ELSE 'Some Other State' END AS StateName FROM pubs.dbo.authors This query will return three columns. The third column, The second form of CASE is the searched CASE. In this format, CASE is evaluating a series of boolean expressions. It returns the first expression that evaluates to true. SELECT CASE WHEN state = 'KS' THEN 'In Kansas' WHEN state = 'ND' THEN 'Up North' ELSE 'Click your heels' END FROM pubs.dbo.authors This CASE statement will run through each WHEN clause until it finds a true one. If they all evaluate to false it will return the ELSE clause. In both cases if there is no ELSE clause it will return a NULL. In the second example, each boolean expression is independant of each other statement. In this example: SELECT CASE WHEN state = 'KS' THEN 'In Kansas' WHEN city = 'New York' THEN 'East I think' ELSE 'Click your heels' END FROM pubs.dbo.authors I can actually compare different columns. Remeber that it searches through the WHEN clauses from top to bottom so order them carefully. Happy coding :) |
- Advertisement - |