ryxxlong的博客 Sql server 中的 CASE 语句文章, 链接 http://ryxxlong.iteye.com/blog/531221 写的比较详细,具体内容如下,主要用于自己以后方便查询 CASE 具有两种式: Simple CASE function: CASE input_expression WHEN when_expression THEN result_ex
ryxxlong的博客Sql server 中的 CASE 语句文章,链接http://ryxxlong.iteye.com/blog/531221
写的比较详细,具体内容如下,主要用于自己以后方便查询
CASE 具有两种格式:
Simple CASE function: CASE input_expression
WHEN when_expression THEN result_expression
[ ...n ]
[
ELSE else_result_expression
]
END
Searched CASE function:
CASE
WHEN Boolean_expression THEN result_expression
[ ...n ]
[
ELSE else_result_expression
]
END
A. 使用带有简单 CASE 函数的 SELECT 语句
在 SELECT 语句中,简单 CASE 函数仅检查是否相等,而不进行其他比较。以下示例使用 CASE 函数更改产品系列类别的显示,以使这些类别更易理解。
USE AdventureWorks;
GO
SELECT ProductNumber, Category =
CASE ProductLine
WHEN 'R' THEN 'Road'
WHEN 'M' THEN 'Mountain'
WHEN 'T' THEN 'Touring'
WHEN 'S' THEN 'Other sale items'
ELSE 'Not for sale'
END,
Name
FROM Production.Product
ORDER BY ProductNumber;
GO
B. 使用带有简单 CASE 函数和 CASE 搜索函数的 SELECT 语句
在 SELECT 语句中,CASE 搜索函数允许根据比较值在结果集内对值进行替换。下面的示例根据产品的价格范围将标价显示为文本注释。
USE AdventureWorks;
GO
SELECT ProductNumber, Name, 'Price Range' =
CASE
WHEN ListPrice = 0 THEN 'Mfg item - not for resale'
WHEN ListPrice < 50 THEN 'Under $50'
WHEN ListPrice >= 50 and ListPrice < 250 THEN 'Under $250'
WHEN ListPrice >= 250 and ListPrice < 1000 THEN 'Under $1000'
ELSE 'Over $1000'
END
FROM Production.Product
ORDER BY ProductNumber ;
GO
以上内容来自Sql server 2005帮助文档
其他Case语句实例:
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 |
这是 CASE 的典型用法,但是使用 CASE 其实可以做更多的事情。比方说下面的 GROUP BY 子句中的 CASE:
SELECT 'Number of Titles', Count(*) FROM titles GROUP BY 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 |
你甚至还可以组合这些选项,添加一个 ORDER BY 子句,如下所示:
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 BY 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 BY 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 |
注意,为了在 GROUP BY 块中使用 CASE,查询语句需要在 GROUP BY 块中重复 SELECT 块中的 CASE 块。
这部分内容来自: http://database.ctocio.com.cn/tips/76/7000576.shtml
注意:Simple CASE Function不能用来判断null值.
如果 case 表达式1 null then 0 else 表达式2, 它永远是执行表达式2,即使表达式1的值是null
应该这样写: case when 表达式1 is null then 0 else 表达式,