首页 新闻 会员 周边

数据库高手进 问题神奇

0
悬赏园豆:20 [已关闭问题]

这是一个语句

select
case  cast(rand()*10 as int)%4
when 0 then 0
when 1 then 1
when 2 then 2
when 3 then 3
else 4 end

这样执行的结果经常出现一个  4   ?? 为什么啊

 

这样写 就不会出现4   select cast(rand()*10 as int)%4

 

if(abs(checksum(newid()))%4='')
begin
print '123'
end

 

if(abs(checksum(rand()))%4='')
begin
print '123'
end

以上2个结果也经常出现 123 为什么了。

 

把问题发到了首页,急切想找到答案哦。

 

问了好多了。还是没有答案。

 

 

 

 

http://www.cnblogs.com/xl888/archive/2009/03/25/1421477.html

 

还有一个问题  大小写不同超时问题

http://www.cnblogs.com/xl888/archive/2009/03/26/1422060.html

 

夏雷的主页 夏雷 | 初学一级 | 园豆:165
提问于:2009-03-26 10:12
< >
分享
其他回答(2)
0

严重建议封掉“上海SB机器”账号及IP段

风海迷沙 | 园豆:4453 (老鸟四级) | 2009-03-26 11:28
0

select 
case  cast(rand()*10 as int)%4 
when 0 then 0
when 1 then 1 
when 2 then 2 
when 3 then 3 
else 4 end

相当于 

if (cast(rand()*10 as int)%4 == 0)

  //print 0

else if (cast(rand()*10 as int)%4 == 1)

     //print 1

 

else if (cast(rand()*10 as int)%4 == 2)

     //print 2

 

else if (cast(rand()*10 as int)%4 == 3)

     //print 3

else 

  //print 4

每次都产生 了随机数,所以才会出现4

使用

DECLARE @d int

SET @d = cast(rand()*10 as int)%4 

SELECT 

case  @d

when 0 then 0

when 1 then 1 

when 2 then 2 

when 3 then 3 

else 4 end

就没有问题了

 

另外 if(0='') 为真 所以会PRINT ‘123’

 

 

Saga | 园豆:205 (菜鸟二级) | 2009-03-26 11:33
0

cast(rand()*10 as int)%4 的意思是从rand()方法返回的随机数乘以10再转换为int类型再余4

公式1:

select 
case  cast(rand()*10 as int)%4 
when 0 then 0
when 1 then 1 
when 2 then 2 
when 3 then 3 
else 4 end

出现4说明有一种情况是值不在0,1,2,3这4个数之中,而公式2:select cast(rand()*10 as int)%4

从来没有出现4并且值一直在0,1,2,3这4个数之中。其实rand()方法返回了float类型带小数的,而int把它转换为正整数之后在余4,select出来的结果当然是正整数没错,但用在比较的情况时它的值有时会带默认带上了小数点那部分去比较。因为公式1带有比较成分,而公式2没带比较成分,所以公式1会出现值不在0,1,2,3这4个数之中的情况,就这样的公式一样:

if cast(rand()*10 as int)%4 < 3 and cast(rand()*10 as int)%4 > 2
begin
     print 'smiting'
end

这样的公式也会经常打印‘smiting’!因为当cast(rand()*10 as int)%4等于2.XXX的时候,如果是直接select出来就不会带上后面的.XXX,因为用到了比较

我们这样来改:

declare @cat int
set @cat = cast(rand()*10 as int)%4
select
case (@cat)
when 0 then 0
when 1 then 1
when 2 then 2
when 3 then 3
else 4 end

就没事了,因为这次拿去做比较的是另一个int类型变量@cat

Cien | 园豆:205 (菜鸟二级) | 2009-03-26 15:07
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册