大家来帮我看看,这个随机能否实现
有一个表 A 结构如下
ID(int自动加1) Name(varchar) value(int)
有3W条左右的数据,其中有2000条左右的记录,VALUE值是> 0的,其他记录 value都为0
现在有个要求就是,更新该表Value为0的记录,设置VALUE为大于1的随机数字,而且还要求
更新的数量为总数量(value为0的数量)的1/3,也就是3条为0的记录里头只更新一条。
并且,更新的记录位置不能有规律,隔一条更新,隔两条更新都不行,位置也要随机
谢谢大家拉
------解决方案--------------------create table tb(id int)
update tb
set id=(select top 1 a from (select 2 as 'a '
union select 3 union select 4 union select 5 union select 6 union select 7
union select 8 union select 9)ta order by newid())
更新为2—9的随机数
------解决方案-------------------- update A set value=cast(rand() *1000 as int)
where value=0 and id in (select top 33 percent id from A)
注释:
cast(rand() *1000 as int) 可以返回小于一千的整数
------解决方案----------------------生成测试数据
create table A(ID int identity(1,1),Name varchar(10),value int)
insert into A select 'AAAA ',0
insert into A select 'BBBB ',0
insert into A select 'CCCC ',1
insert into A select 'DDDD ',0
insert into A select 'EEEE ',3
insert into A select 'FFFF ',0
insert into A select 'GGGG ',0
insert into A select 'HHHH ',5
insert into A select 'IIII ',0
insert into A select 'JJJJ ',7
go
--获取更新目标行数
declare @count int,@id int
select @count=count(*)/3 from A where value=0
--锁定待更新行ID
set rowcount @count
select id into # from A order by newid()
set rowcount 0
--借助游标循环更新数据
declare tc cursor for
select id from #
open tc
fetch next from tc into @id
while @@fetch_status=0
begin
update A set value=9*RAND()+1 where id=@id
fetch next from tc into @id
end
close tc
deallocate tc
go
--查看更新结果
select * from A
go
--删除测试数据
drop table A,#
go
------解决方案--------------------rand(checksum(newid())) 这样用就不同一SQL语句中就不唯一了