T-SQL 中的 CASE

作者:leen 来源:ITPOW(原创) 日期:2006-10-17

T-SQL 中的 CASE 与其它高级语言的 CASE 意义相同,用法也基本相同,不过 T-SQL 中具有两种形式。

一、简单 CASE 函数(与其它语言相同的形式):
CASE input_expression
  WHEN when_expression THEN result_expression
  [ ...n ]
  [ ELSE else_result_expression ]
END

当 input_expression 等于 when_expression 时返回对应的 result_expression,如果与所有的 when_expression 都不相等,返回 else_result_expression。

when_expression 是简单的表达式,比如:3-2、3.1、x*3。不能是 >3 之类的形式。

示例:
select case stor_id
  when '7131' then stor_id+'*'
  when '7066' then stor_id+'**'
  else stor_id
end as stor_id
, ord_num, ord_date, qty, payterms, title_id from sales

这是在 SQL 中使用 CASE 的一个示例,使用的数据库是 SQL Server 自带的示例数据库 pubs,如果 stor_id 是 7131 就在其后面加一个 *,如果是 7066 就加两个 *,其它情况直接输出 stor_id。

二、CASE 搜索函数:
CASE
  WHEN boolean_expression THEN result_expression
  [ ...n ]
  [ ELSE else_result_expression ]
END

这种形式下,可以比较不单单是“等于”的情况。

示例:
print case
  when 1>2 then '1>2 返回 true'
  when 4<3 then '4<3 返回 true'
  else '1>2 返回 false,4<3 也返回 false'
 end

由于 1>2、4<3 均返回 false,所以最终将显示:1>2 返回 false,4<3 也返回 false

相关文章