纠正:格式1的字段2后面应该有个‘逗号’
错误格式:
select 字段1,字段2
case 字段1
when 条件表达式1, then 结果表达式1
end
from 表
分层结构图:
外层是selct * from 表的结构
里层是case when结构
举例1:
定义一个变量,当变量为2时输出字符串’var is 2‘,当变量为1时输出字符串’var is 1‘,当变量为不等于1和2时输出字符串’var is not 1 or 2‘
DECLARE @var INT;
SET @var=2
select
CASE
WHEN @var=2 THEN 'var is'+convert(varchar(9),@var)
WHEN @var=1 THEN 'var is 1'
ELSE 'var is not 1 or 2'
END
举例2:
输出b等于1,2或其他值时的字符串
select b,
CASE b
WHEN '2' THEN 'var is 2'
WHEN '1' THEN 'var is 1'
ELSE 'var is not 1 or 2'
END
from t1
结果: