IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_save_comefrom_newviaord2]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_save_comefrom_newviaord2]
GO
CREATE procedure [dbo].[mps_save_comefrom_newviaord2] 
@bsid int,
@newviaord2 int
as
begin
update mps_biztype_comefrom SET bs_newviaord2=@newviaord2where bs_id=@bsid 

   
   declare @bizid int 
   select top 1 @bizid = bs_bizid from mps_biztype_comefrom where bs_id=@bsid 
   -- fix data 
   -- 看看有没有  bs_newviaord2=0 bs_ord2tag>0 的情况
   declare @t table(bsid int , ord2tag int ) 
   insert into @t(bsid) 
   select bs_id from mps_biztype_comefrom 
   where bs_bizid=@bizid and bs_newviaord2=0 and bs_ord2tag>0 
   update mps_biztype_comefrom set bs_ord2tag=0 from @t where bs_id=bsid 
   update mps_biztype_comefrom_fieldmap set bsf_use=1 from @t where bsf_bsid=bsid 
   
   -- 看看有没, bs_newviaord2>0 bs_ord2tag=0  的情况 
   delete @t 
   insert into @t(bsid,ord2tag) 
   select bs_id,0 from mps_biztype_comefrom 
   where bs_bizid=@bizid and bs_newviaord2>0 and bs_ord2tag=0 and bs_sord2tag>0 
   
   declare @tt table(ord2 int)
   insert into @tt(ord2) 
   select distinct biz2_tag 
   from mps_biztype2 
   where biz2_bizid=@bizid  and biz2_tag>0 
   
   delete @tt 
   from mps_biztype_comefrom 
   where bs_bizid=@bizid and bs_ord2tag=ord2  
   
   
   update @t set ord2tag = ord2 from @tt 
   
   
   update mps_biztype_comefrom set bs_ord2tag=ord2tag from @t where bs_id=bsid 
   update mps_biztype_comefrom_fieldmap set bsf_use=1 from @t where bsf_bsid=bsid 
   
   declare @ord2t int 
   select top 1 @ord2t = biz2_tag from mps_biztype2 where biz2_bizid=@bizid and biz2_tag>0 
   set @ord2t = isnull(@ord2t,0) 
   update mps_biztype_comefrom set bs_ord2tag=@ord2t where bs_bizid=@bizid and ((bs_ord2tag is null ) or (bs_ord2tag=0)) and  bs_sord2tag>0 and bs_newviaord2>0 
   
   update  mps_biztype_comefrom_fieldmap set bsf_use=1 where  bsf_bsid=@bsid   
   
end