2011-06-15 28 views
2

出於測試目的,我想通過將colums中的位設置爲隨機值來更新表。如何翻轉SQL中的隨機位

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

它似乎工作,因爲它應該但沒有辦法,我想它。我想這個問題是結果將大部分時間高於1

我怎樣才能翻轉隨機位隨機值

回答

6

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 
+0

if/else是否會對性能造成嚴重影響?現在不是這種情況,而是爲了以後使用這種模式? – 2011-06-15 12:20:56

+0

我不會這麼想,昂貴的rand(cast(newid()..只會被評估一次,再加上你可以改變它來引入偏見。 – 2011-06-15 12:22:13

+0

works ..謝謝! – 2011-06-15 12:27:09

0

如何

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

這是行不通的。 – 2011-06-15 12:47:48

+0

以什麼方式?它適用於我在SQL Server 2008 R2上,你使用的是哪個版本? – alnorth29 2011-06-15 14:50:18

+0

這將所有行的位數翻轉爲相同的值:) – 2011-06-15 16:53:07

1

取決於你有多少位字段使用,您可以生成所有的使用這樣的事情可能的設置:

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