【问题标题】:How to flip random bits in SQL如何在 SQL 中翻转随机位
【发布时间】:2011-06-15 12:09:19
【问题描述】:

出于测试目的,我想通过将列中的位设置为随机值来更新表。

update [Planned] 
set [IsPlannable] = 1 * rand(cast(cast(newid() as binary(8)) as int))
WHERE [ComputerID] > 100

它似乎确实可以正常工作但不是我想要的方式。我想问题是结果大多数时候会高于 1。

如何将随机位转换为随机值

【问题讨论】:

    标签: tsql sql-server-express


    【解决方案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
    

    【讨论】:

    • if/else 是否会对性能产生严重影响?不是现在是这样,而是为了以后使用这种模式?
    • 我没想到,昂贵的 rand(cast(newid().. 只会被评估一次,而且你可以改变它来引入偏见。
    【解决方案2】:

    根据您必须使用的位域数量,您可以使用以下方式生成所有可能的设置:

    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
    

    【讨论】:

      【解决方案3】:

      怎么样

      cast(round(rand(), 0) as bit)
      

      【讨论】:

      • 以什么方式?我在 SQL Server 2008 R2 上运行良好,您使用的是哪个版本?
      • 这会将位翻转为所有行相同的单个值:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 2017-07-21
      • 1970-01-01
      • 1970-01-01
      • 2021-02-17
      • 2021-01-18
      相关资源
      最近更新 更多