出于测试目的,我想通过将colums中的位设置为随机值来更新表。如何翻转SQL中的随机位
update [Planned]
set [IsPlannable] = 1 * rand(cast(cast(newid() as binary(8)) as int))
WHERE [ComputerID] > 100
它似乎工作,因为它应该但没有办法,我想它。我想这个问题是结果将大部分时间高于1
我怎样才能翻转随机位到随机值?
出于测试目的,我想通过将colums中的位设置为随机值来更新表。如何翻转SQL中的随机位
update [Planned]
set [IsPlannable] = 1 * rand(cast(cast(newid() as binary(8)) as int))
WHERE [ComputerID] > 100
它似乎工作,因为它应该但没有办法,我想它。我想这个问题是结果将大部分时间高于1
我怎样才能翻转随机位到随机值?
的1 *
仍然产生鉴于cast(0.1 as bit)
将一代产量1,这将cast(0.9 as bit)
更新都设置为1。
,你可以一个小数&;
update Planned set IsPlannable = case when rand(cast(newid() as binary(8))) < 0.5 then 0 else 1 end
如何
cast(round(rand(), 0) as bit)
这是行不通的。 – 2011-06-15 12:47:48
以什么方式?它适用于我在SQL Server 2008 R2上,你使用的是哪个版本? – alnorth29 2011-06-15 14:50:18
这将所有行的位数翻转为相同的值:) – 2011-06-15 16:53:07
取决于你有多少位字段使用,您可以生成所有的使用这样的事情可能的设置:
with test as (
select 0 as myId, cast(0 as bit) col1, cast(0 as bit) col2, cast(0 as bit) col3
union all
select myId + 1,
case when myId & 1 = 1 then cast(1 as bit) else cast(0 as bit) end,
case when myId & 2 = 2 then cast(1 as bit) else cast(0 as bit) end,
case when myId & 4 = 4 then cast(1 as bit) else cast(0 as bit) end
from test
where myId<100
)
select distinct col1, col2, col3 from test
if/else是否会对性能造成严重影响?现在不是这种情况,而是为了以后使用这种模式? – 2011-06-15 12:20:56
我不会这么想,昂贵的rand(cast(newid()..只会被评估一次,再加上你可以改变它来引入偏见。 – 2011-06-15 12:22:13
works ..谢谢! – 2011-06-15 12:27:09