>我有以下代码
set @string:='11';
select CASE @string
WHEN CAST(@a AS SIGNED)=11 THEN 'yes'
ELSE 'no'
END as filed;
我不明白为什么它返回"否"。
而且如果我使用WHEN @string='11' THEN 'yes'
它也返回 no。
这就是你的目标吗?
set @string:='11';
select CASE WHEN CAST(@string AS SIGNED)='11' THEN 'yes' ELSE 'no' END as filed;
也可以表示为
set @string:='11';
select CASE CAST(@string AS SIGNED) when '11' THEN 'yes' ELSE 'no' END as filed;
set @string:='11';
select CASE WHEN CAST(@string AS SIGNED) = 11 THEN 'yes'
ELSE 'no'
END as filed;
演示
因为您尚未定义@a
,所以值为NULL
。
因此,ELSE
子句将始终返回。
那么你的第二个问题是这不起作用:
set @a = '11';
SELECT CASE @a
WHEN CAST(@a AS SIGNED) = 11 THEN 'yes'
ELSE 'no'
END as filed;
这是因为CAST(@a AS SIGNED) = 11
是一个布尔表达式,其值为0
、1
或NULL
,并且永远不会11
。
这些确实有效:
SELECT CASE WHEN CAST(@a AS SIGNED) = 11 THEN 'yes'
ELSE 'no'
END as filed;
SELECT CASE @a WHEN 11 THEN 'yes'
ELSE 'no'
END as filed;