如何在SQL中翻转随机位

| 为了进行测试,我想通过将列中的位设置为随机值来更新表。
update [Planned] 
set [IsPlannable] = 1 * rand(cast(cast(newid() as binary(8)) as int))
WHERE [ComputerID] > 100
它似乎确实可以正常工作,但不是我想要的方式。我想问题是大多数情况下结果会高于1。 如何将随机位翻转为随机值?     
已邀请:
        
1 *
仍将产生分数,并且假定given2ѭ得1,as3ѭ则更新均设置为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)
    

要回复问题请先登录注册