CREATE PROCEDURE [dbo].[proc_user_goshop_update]
@goshop_modify_date varchar(10)='' --日期,默认今天,格式:yyyy-mm-dd
,@batchsize int=100 --批次数量
,@waitfordelay int=3 --批次等待时间(秒)
AS
BEGIN
set nocount on
set xact_abort on
declare @cal_date datetime --计算日期
declare @sql_user nvarchar(4000) --动态SQL_user
declare @sql_shop nvarchar(4000) --动态SQL_shop
declare @n int --分表ID
declare @i int --循环ID
declare @row_count_user int --user记录数
declare @row_count_shop int --shop记录数
set @n=0
-- 初始化日期
if @goshop_modify_date='' or isdate(@goshop_modify_date)=0
begin
set @cal_date=convert(varchar(10),getdate(),120)
end
else
begin
set @cal_date=@goshop_modify_date
end
create table #temp_user(id int identity(1,1) primary key,userid int)
create table #temp_shop(id int identity(1,1) primary key,shopid int,go_count int)
while @n<10
begin
set @sql_user='select userid from openquery(mysql62,''select distinct userid from 51fanli_fun.tb_goshop_tracking_ticket_'+convert(varchar,@n)+' where ctime>=unix_timestamp('''''+convert(varchar(10),@cal_date,120)+''''');'')'
set @sql_shop='select shopid,go_count from openquery(mysql62,''select shopid,count(1) go_count from 51fanli_fun.tb_goshop_tracking_ticket_'+convert(varchar,@n)+' where ctime>=unix_timestamp('''''+convert(varchar(10),@cal_date,120)+''''') group by shopid;'')'
set @row_count_user=0
set @row_count_shop=0
truncate table #temp_user
truncate table #temp_shop
insert into #temp_user(userid)
exec sp_executesql @sql_user
select @row_count_user=@@rowcount
insert into #temp_shop(shopid,go_count)
exec sp_executesql @sql_shop
select @row_count_shop=@@rowcount
-- dv_user
-- 如果用户的dv_user.active=0,则认为是新注册用户,点击“去商城”后,更新dv_user.active=1
set @i=0
while @i<@row_count_user
begin
update dv_user
set active=1
from #temp_user t
inner loop join dv_user u
on u.userid=t.userid
where t.id between @i+1 and @i+@batchsize
and u.active=0
set @i=@i+@batchsize
waitfor delay @waitfordelay
end
-- product,productview
-- 更新商城每天购物点击次数
set @i=0
while @i<@row_count_shop
begin
begin tran
update product
set viewhistory=viewhistory+t.go_count
from #temp_shop t
inner loop join product p
on t.shopid=p.id
where t.id between @i+1 and @i+@batchsize
update productview
set viewnum=viewnum+t.go_count
from #temp_shop t
inner loop join productview pv
on t.shopid=pv.shopid
where t.id between @i+1 and @i+@batchsize
and pv.viewdate>@cal_date
and pv.viewdate<=dateadd(day,1,@cal_date)
insert into productview(viewdate,shopid,viewnum)
select convert(varchar(10),@cal_date,120)+right(convert(varchar(19),getdate(),120),9),t.shopid,t.go_count
from #temp_shop t
left loop join productview pv with(nolock)
on t.shopid=pv.shopid and pv.viewdate>@cal_date and pv.viewdate<=dateadd(day,1,@cal_date)
where t.id between @i+1 and @i+@batchsize
and pv.shopid is null
commit
set @i=@i+@batchsize
waitfor delay @waitfordelay
end
set @n=@n+1
end
END