IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_save_subselectedusers]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_save_subselectedusers]
GO
create procedure [dbo].[mps_save_subselectedusers]
  @cuid bigint ,
  @subcuids varchar(max)
as
begin
  SET NOCOUNT ON

    declare @rowEffect int,
      @idx int ,
      @subcuid varchar(20) --,@tmpstr varchar(max) = ''
    
    declare @tmptable table(cscuid bigint ,cssubcuid bigint)
    
    while(@subcuids>'')
    begin
    set @idx = CHARINDEX(',',@subcuids)
    if(@idx>0) 
    begin
      set @subcuid = substring(@subcuids,1,@idx-1)
      set @subcuids = substring(@subcuids,@idx+1,len(@subcuids))  
    end
    else
    begin
      set @subcuid = @subcuids
      set @subcuids = ''
    end
                      
    insert into @tmptable(cscuid,cssubcuid)
    values(@cuid,@subcuid)
            
    end
    
    insert into mps_employee_subusers(cs_cuid,cs_subcuid)
    select cscuid ,cssubcuid
    from @tmptable 
    where not exists(select 1 from mps_employee_subusers with(nolock) where cs_cuid = cscuid and cs_subcuid = cssubcuid)                         
    and cscuid <> cssubcuid

    exec mps_calculate_relationship

    select  'ok' result          
      --返回所有关系
    select cu.cu_name fname,t.cus_cuid fcuid,sbcu.cu_name  sname,t.cus_subcuid scuid
    from mps_employee_subusersreal t,
        mps_employee cu,
        mps_employee sbcu 
    where cu.cu_id = cus_cuid 
    and cus_subcuid = sbcu.cu_id
    --and cu.cu_name = '刘小松'  

    set nocount off 

end