开发者

update random numbers for top 100 rows in sql?

I need to update random numbers for top 100 rows (a field) in sql. random number should be less tha开发者_如何学编程n 100. how to do that?


In SQL 2008

update top (100) MyTable
set MyField = cast(cast(crypt_gen_random(1) as int) * 100.0 / 256 as int)

I believe the same will work in SQL 2005.

[Edit]

If it doesn't work in SQL 2005, you can do this:

update top (100) MyTable
set MyField = abs(cast(newid() as binary(6)) % 100)


Pretty sure this is ok in 2k5;

--add rows numbers
;with ROWS(id, fld, rownum) as 
(
    select id, fld, 
    row_number() over (order by id asc) --this order defines your "top" 
    from tablename
)
update tablename
  set fld = 1 + abs(checksum(newid())) % 100 --dont use rand() as it will give the same value
  from ROWS inner join tablename on tablename.id = ROWS.id
  where rownum between 1 and 100 --limit to 100 rows
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜