首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

一条sql语句有关问题

2012-05-24 
一条sql语句问题select case cast(rand()*3 as int)when 0 then 缺货时,请联系我 when 1 then 缺货

一条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 onselect case cast(rand()*3 as int)when 0 then 0 when 1 then 1 when 2 then 2end  FROM  [sys].[columns] 

热点排行