简单随机更新——newid()

发布时间:2022-07-05 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了简单随机更新——newid()脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

newid()生成的是uniqueidentifier类型的唯一值,因此可以作为随机排序的参照字段

考虑以下场景:

有n个消费者分布在全国各地,由每地的会员店来维护,每个会员有若干个导购,假定有m个会员店,每个会员店的导购数量为a,a>=0,现在要将会员店的导购随机分配到每个消费者,如果该会员店没有导购,则暂不维护。

消费者与会员店一对一关系;会员店与导购一对多关系;

--会员关系表
create table tableA (rankid int,clientid int,retailer int,promotor int)
--会员店与导购关系表
create table tableB (retailer int,PRomotor int)
--while方法实现
declare @num int =1,@maxid int
select @maxid=MAX(rankid) From tableA 
while @num<=@maxid
begin
  declare @promotor int=0 ,@retailer int=0
  select @retailer =retailer from tableA where rankid=@num
  select top 1 @promotor = promotor from tableB b where b.Retailer=@retailer order by NEWID() 
  if @promotor is null  set @promotor =0
  
  update tableA set promotor= @promotor where rankid=@num
  
  set @num=@num+1
end
--游标方法实现
declare @clientid int
declare mycursor cursor for   
select clientid from tableA
oPEn mycursor 
fetch next from mycursor into @clientid    
while (@@fetch_status=0)  
begin      
   
   declare @promotor1 int=0 ,@retailer1 int =0
   select @retailer1 =retailer from tableA where clientid=@clientid
   select top 1 @promotor1 = promotor from tableB b where b.Retailer=@retailer1 order by NEWID() 
   if @promotor1 is null  set @promotor1 =0
  
   update tableA set promotor= @promotor1 where clientid=@clientid
   fetch next from mycursor into @clientid
end  
close mycursor 
DEALLOCATE mycursor 

&nbsp;

脚本宝典总结

以上是脚本宝典为你收集整理的简单随机更新——newid()全部内容,希望文章能够帮你解决简单随机更新——newid()所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。