Case when syntax in SQL
Is there a switch case statement similar to the C language in SQL ??
No. Use case when instead.
For example, the following statement shows the Chinese year and month
Select getdate () as date, Case month (getdate ())
When 11 then '11'
When 12 then '12'
Else substring ('february 5, 1234, 80 or 90 ', month (getdate (), 1)
End + 'month' as month
========================================================== ==========
Case may be one of the keywords most misused in SQL. Although you may have used this keyword before to create a field, it also has more features. For example, you can use case in the WHERE clause.
First, let's take a look at the case syntax. In a general SELECT statement, the syntax is as follows:
Select <mycolumnspec> =
Case
When <A> then <somethinga>
When <B> then <somethingb>
Else <somethinge>
End
In the above Code, you need to replace the content in angle brackets with specific parameters. The following is a simple example:
Use pubs
Go
Select
Title,
'Price range' =
Case
When price is null then 'unpriced'
When price <10 then 'bargain'
When price between 10 and 20 then 'average'
Else 'Gift to impress relatives'
End
From titles
Order by price
Go
This is a typical example of case, but you can do more with case. For example, the case in the group by clause below:
Select 'number of tidles ', count (*)
From titles
Group
Case
When price is null then 'unpriced'
When price <10 then 'bargain'
When price between 10 and 20 then 'average'
Else 'Gift to impress relatives'
End
Go
You can even combine these options to add an order by clause, as shown below:
Use pubs
Go
Select
Case
When price is null then 'unpriced'
When price <10 then 'bargain'
When price between 10 and 20 then 'average'
Else 'Gift to impress relatives'
End as range,
Title
From titles
Group
Case
When price is null then 'unpriced'
When price <10 then 'bargain'
When price between 10 and 20 then 'average'
Else 'Gift to impress relatives'
End,
Title
Order
Case
When price is null then 'unpriced'
When price <10 then 'bargain'
When price between 10 and 20 then 'average'
Else 'Gift to impress relatives'
End,
Title
Go
Note: To use case in the group by block, the query statement must repeat the case block in the select block in the group by block.
In addition to selecting custom fields, case is useful in many cases. Further, you can get the grouping sorting result set that you previously thought was impossible to get.
From: http://www.cnblogs.com/qiantuwuliang/archive/2009/06/03/1495770.html