日期:2014-05-18  浏览次数:20410 次

一条sql语句问题
select case cast(rand()*3 as int)
when '0' then '缺货时,请联系我 ' 
when '1' then '缺货时,将有货的商品发出,取消无货商品的订购' 
when '2' then '缺货时,取消此订单'
end 

问一下,这个SqServer语句为什么会出现null呢?
rand生成任意小数,然后*3,生成的数应该就在0.1.2三个数之中阿。

------解决方案--------------------
SQL code


declare @i int 
set @i = cast(rand()*3 as int)
select case 
when @i =0 then '缺货时,请联系我 '  
when @i =1 then '缺货时,将有货的商品发出,取消无货商品的订购'  
when @i =2 then '缺货时,取消此订单'
else convert(char(1),@i)
end

------解决方案--------------------
解释一下这个问题,我也是从微软论坛得来的一个比较靠谱的解释:
针对一个不能确定的值(通过RAND()函数),每一个when,rand()*3都会重新计算一次,其实就相当于:
when cast(rand()*3 as int)=0 then 0
when cast(rand()*3 as int)=1 then 1
when cast(rand()*3 as int)=2 then 2
如果都不成立,那就是else,也就是null了。

借助一个表,通过执行计划可以印证这个结论:
SQL code
set statistics profile on
select case cast(rand()*3 as int)
when 0 then 0 
when 1 then 1 
when 2 then 2
end  
FROM  [sys].[columns]