<p class="intro">sql语言中有没有类似C语言中的switch case的语句?</p> 没有,用case when 来代替就行了. <br><br>例如,下面的语句显示中文年月 <br> 代码如下: <br>select getdate() as 日期,case month(getdate()) <br>when 11 then '十一' <br>when 12 then '十二' <br>else substring('一二三四五六七八九十', month(getdate()),1) <br>end+'月' as 月份 <br> <br>CASE 可能是 SQL 中被误用最多的关键字之一。虽然你可能以前用过这个关键字来创建字段,但是它还具有更多用法。例如,你可以在 WHERE 子句中使用 CASE。 <br><br>首先让我们看一下 CASE 的语法。在一般的 SELECT 中,其语法如下: <br> 代码如下: <br>SELECT <mycolumnspec> = <br>CASE <br>WHEN <a> THEN <somethinga> <br>WHEN <b> THEN <somethingb> <br>ELSE <somethinge> <br>END <br> <br>在上面的代码中需要用具体的参数代替尖括号中的内容。下面是一个简单的例子: <br> 代码如下: <br>USE pubs <br>GO <br>SELECT <br>Title, <br>'Price Range' = <br>CASE <br>WHEN price IS NULL THEN 'Unpriced' <br>WHEN price WHEN price BETWEEN 10 and 20 THEN 'Average' <br>ELSE 'Gift to impress relatives' <br>END <br>FROM titles <br>ORDER BY price <br>GO <br> <br>这是 CASE 的典型用法,但是使用 CASE 其实可以做更多的事情。比方说下面的 GROUP BY 子句中的 CASE: <br> 代码如下: <br>SELECT 'Number of Titles', Count(*) <br>FROM titles <br>GROUP BY <br>CASE <br>WHEN price IS NULL THEN 'Unpriced' <br>WHEN price WHEN price BETWEEN 10 and 20 THEN 'Average' <br>ELSE 'Gift to impress relatives' <br>END <br>GO <br> <br>你甚至还可以组合这些选项,添加一个 ORDER BY 子句,如下所示: <br> 代码如下: <br>USE pubs <br>GO <br>SELECT <br>CASE <br>WHEN price IS NULL THEN 'Unpriced' <br>WHEN price WHEN price BETWEEN 10 and 20 THEN 'Average' <br>ELSE 'Gift to impress relatives' <br>END AS Range, <br>Title <br>FROM titles <br>GROUP BY <br>CASE <br>WHEN price IS NULL THEN 'Unpriced' <br>WHEN price WHEN price BETWEEN 10 and 20 THEN 'Average' <br>ELSE 'Gift to impress relatives' <br>END, <br>Title <br>ORDER BY <br>CASE <br>WHEN price IS NULL THEN 'Unpriced' <br>WHEN price WHEN price BETWEEN 10 and 20 THEN 'Average' <br>ELSE 'Gift to impress relatives' <br>END, <br>Title <br>GO <br> <br>注意,为了在 GROUP BY 块中使用 CASE,查询语句需要在 GROUP BY 块中重复 SELECT 块中的 CASE 块。 <br><br>除了选择自定义字段之外,在很多情况下 CASE 都非常有用。再深入一步,你还可以得到你以前认为不可能得到的分组排序结果集。 </somethinge></somethingb></b></somethinga></a></mycolumnspec>