在开发过程中,常常需要基于条件逻辑返回一个列的值,这时我们需要使用case表达式。

例如,下面的查询到产品表使用案例表达的SELECT语句生成信息描述的CategoryID列的值。

SQL代码如下所示:


-设置数据库上下文
tsqlfundamentals2008使用;


选择ID、产品名称、CategoryID,
案例CategoryID
当1 then'beverages
当2 then'condiments
当3 then'dairy产品
当4 then'confections
当5 then'grains /谷物
当6 then'meat /家禽
当7 then'produce
当8 then'seafood
else'unkown类别
最后将
从生产、产品;


查询结果: