SQL语句–CASE when…
case
when A
then B
else C
end
{case when then else end }这一串,可以直接把他当成 “一个数 ”来看,这个“数”可以放在任何位置,如:select后,where条件中,group by里…
能放数的地方,就能放{case when then else end }这一串,这就能明白为什么不能返回结果集了**
实战总结
关于该函数,嵌套其他内容时,要注意一下几点:
1.A 位置:只能写判断条件
2.B 位置:可以写查询语句,但是该查询结果必须只能有一行一列;
3.B 位置:可以再嵌套一个case when…end
4.C 位置:同B位置
下面举例
1.反例:.A 位置:只能写判断条件
SELECT
CASE
when (select [EmployeeID] from Employee WHERE [EmployeeID]='1002')
then '王敏'
else 'NULL'
END
FROM dbo.Employee
返回提示错误
我们再改成一个判断条件试试
SELECT
CASE
when [EmployeeID]='1002'
then '王敏'
else 'NULL'
END
FROM dbo.Employee
返回结果:OK
2.反例:B 位置:可以写查询语句,但是该查询结果必须只能有一行一列;
SELECT
CASE
when [EmployeeID]='1002'
then (select [EmployeeID] from Employee WHERE [Name]='1')
else 'NULL'
END
FROM dbo.Employee
返回错误提示:
这是因为在Employee 表中,有多个员工的姓名 [Name]=‘1’
执行 select [EmployeeID] from Employee WHERE [Name]=‘1’
返回结果:
而进行判断后的返回值只能有一个,不能返回结果集
所以互相冲突,提示了错误
我们改下then 后的SELECT语句试试
执行 select [EmployeeID] from Employee WHERE [Name]=‘1’ AND EmployeeID=‘2003’
返回结果:
此时只有一行一列
再执行下看看
SELECT
CASE
when [EmployeeID]='1002'
then (select [EmployeeID] from Employee WHERE [Name]='1' AND EmployeeID='2003')
else 'NULL'
END
FROM dbo.Employee
返回结果:OK
3.B 位置:可以再嵌套一个case when…end
case
when A
then -----then下面可以嵌套一个case when
(case
when A
then B
else C
end)
else -----else下面可以嵌套一个case when
(case
when A
then B
else C
end)
end