更新sql中前100行的随机数?

时间:2011-05-07 15:49:09

标签: sql sql-server sql-server-2005 tsql sql-server-2008

我需要在sql中更新前100行(一个字段)的随机数。随机数应小于100.怎么做?

2 个答案:

答案 0 :(得分:12)

在SQL 2008中

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

我相信同样适用于SQL 2005。

<强> [编辑]

如果它在SQL 2005中不起作用,您可以这样做:

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

答案 1 :(得分:0)

非常确定这在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