日期:2014-05-18  浏览次数:20424 次

update rand
比如 table 用100条数据

现在 想将total更新为 30 到 49 的 随机数
update table set total = CAST( FLOOR(RAND()*20 + 30) AS INT)

但是 更新之后 每条 数据生成的随机数是一样的。。
不是想要的效果,
求助

------解决方案--------------------
SQL code

go
create table #tbl
(
id int identity(1,1),
value int
)
declare @a int
set @a=1
while @a<=100
begin
insert #tbl(value)
select cast(FLOOR(RAND()*20 + 30) as int)
set @a=@a+1
end
update [table] set total=value
from #tbl a where a.id=[table].col

--你那个实际上就产生了一个随机数,然后付给了你的表total字段的那一百航

------解决方案--------------------
清空表数据这样:
SQL code

truncate table #tbl

------解决方案--------------------
SQL code
--新建临时表#tb
create table #tb(id int identity(1,1) not null,num int null)
insert into #tb values (43),(54),(54),(43),(65),(56),(65),(63)
select * from #tb

--通过表变量,循环遍历#tb中每一条记录,并且更新num字段
declare @tab table(id int null,num1 int null)
insert into @tab select * from #tb 
declare @i int =0,@tempId int =0
while @i<(select COUNT(*) from @tab)
begin
SET ROWCOUNT 1
SELECT @tempId=[id] FROM @tab
SET ROWCOUNT 0   
update #tb set num=cast(FLOOR(RAND()*20 + 30) as int) where id=@tempId
delete from @tab where id=@tempId
end