【发布时间】:2011-06-15 12:09:19
【问题描述】:
出于测试目的,我想通过将列中的位设置为随机值来更新表。
update [Planned]
set [IsPlannable] = 1 * rand(cast(cast(newid() as binary(8)) as int))
WHERE [ComputerID] > 100
它似乎确实可以正常工作但不是我想要的方式。我想问题是结果大多数时候会高于 1。
如何将随机位转换为随机值?
【问题讨论】:
出于测试目的,我想通过将列中的位设置为随机值来更新表。
update [Planned]
set [IsPlannable] = 1 * rand(cast(cast(newid() as binary(8)) as int))
WHERE [ComputerID] > 100
它似乎确实可以正常工作但不是我想要的方式。我想问题是结果大多数时候会高于 1。
如何将随机位转换为随机值?
【问题讨论】:
1 * 仍然产生一个小数,并且鉴于 cast(0.1 as bit) 和 cast(0.9 as bit) 将产生 1,更新都设置为 1。
你可以;
update Planned set IsPlannable = case when rand(cast(newid() as binary(8))) < 0.5 then 0 else 1 end
【讨论】:
根据您必须使用的位域数量,您可以使用以下方式生成所有可能的设置:
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
【讨论】:
怎么样
cast(round(rand(), 0) as bit)
【讨论】: