IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_g_biz_ord2tags]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_g_biz_ord2tags]
GO
CREATE procedure [dbo].[mps_g_biz_ord2tags] 
@bizid int,
@stype varchar(10),
@sbizid int
 as
begin
  set nocount on  
  -- 先增加主对主
  if (not exists(select bs_id from mps_biztype_comefrom 
where bs_bizid=@bizid and bs_stype=@stype and bs_sbizid=@sbizid and bs_sord2tag=0))
  begin
  insert into mps_biztype_comefrom(bs_bizid,bs_ord2tag,bs_stype,bs_sbizid,bs_sord2tag,bs_sord2group) 
  values(@bizid,0,@stype ,@sbizid,0,'') 
  end 
  -- 检查一下，有没有多余的明细源
  delete   mps_biztype_comefrom 
  where bs_bizid=@bizid and bs_stype=@stype and bs_sbizid=@sbizid and bs_sord2tag>0 and 
  (not exists (select * from mps_biztype2 where biz2_bizid=@sbizid and biz2_tag>0 and biz2_tag=bs_sord2tag))
  -- 插入没有的
  insert into mps_biztype_comefrom(bs_bizid,bs_stype,bs_sbizid,bs_sord2tag,bs_sord2group) 
  select @bizid,@stype ,@sbizid,biz2_tag,'' 
  from mps_biztype2
  where biz2_bizid=@sbizid and biz2_tag>0 and 
    (not exists (select bs_id from mps_biztype_comefrom 
where   bs_bizid=@bizid and bs_stype=@stype and  bs_sbizid=@sbizid and 
    biz2_tag>0 and biz2_tag=bs_sord2tag )) 
   
   update  mps_biztype_comefrom set 
bs_scaption = biz_title 
   from mps_biztype 
   where bs_bizid=@bizid and bs_stype=@stype and  bs_sbizid=@sbizid and biz_id=bs_sbizid 
   
   update  mps_biztype_comefrom set 
bs_scaption_detail = '' 
   where bs_bizid=@bizid and bs_stype=@stype and  bs_sbizid=@sbizid and  bs_sord2tag= 0 
   
   update  mps_biztype_comefrom set 
bs_scaption_detail = biz2_caption 
   from mps_biztype2 
   where bs_bizid=@bizid and bs_stype=@stype and  bs_sbizid=@sbizid and 
bs_sbizid=biz2_bizid and biz2_tag>0 and biz2_tag=bs_sord2tag 
   
select biz2_bizid,biz2_tag,biz2_group,biz2_caption,case when biz2_group='' then biz2_caption else biz2_caption+'-'+biz2_group end biz2_sourcename 
from mps_biztype2 where biz2_bizid=@sbizid  and  biz2_tag>0  order by biz2_tag,biz2_group 
  set nocount off
end