IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_save_adjustdepart]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_save_adjustdepart]
GO
CREATE procedure [dbo].[mps_save_adjustdepart]  
  -- Add the parameters for the stored procedure here  
  @cmpid int,  
  @branchid int,  
  @dpids varchar(max)  
AS  
BEGIN  
  -- SET NOCOUNT ON added to prevent extra result sets from  
  -- interfering with SELECT statements.  
  SET NOCOUNT ON;  
  DECLARE @temporary table(dpid int)  
  DECLARE @code varchar(30)  
  DECLARE @depart nvarchar(100)  
  DECLARE @order int  
  DECLARE @level int  
  DECLARE @id int  
  DECLARE @i int = 0  
  DECLARE @j int = 0  
  DECLARE @dp_id varchar(50) = 0  
  DECLARE @ids varchar(max) = @dpids + ','  
  WHILE LEN(@ids) > 0  
  BEGIN  
  
    --生成临时表存储要更新的id  
    SET @i = CHARINDEX(',',@ids)  
    if(@i>0)  
    begin  
      SET @dp_id = SUBSTRING(@ids,1,@i-1)  
      SET @ids = SUBSTRING(@ids,@i+1,LEN(@ids))  
    end  
    else  
    begin  
      SET @dp_id = @ids  
      SET @ids = ''  
    end  
    IF LEN(@dp_id) > 0  
    BEGIN  
      INSERT INTO @temporary(dpid)  
      VALUES (CONVERT(int,@dp_id))  
    END  
    
    
    --插入表中没有的记录  
    SELECT @j = COUNT(*)  
    FROM mps_depart  
    WHERE dp_bcid = @branchid  
      AND dp_dpstdid = @dp_id  
  

  
    SET @j = ISNULL(@j,0)  
    IF @j = 0  
    BEGIN  
      SELECT @code=dp_code,  
          @depart=dp_depart,  
          @order=dp_order,  
          @level=dp_level  
      FROM mps_depart_base  
      WHERE dp_id=@dp_id  
      AND dp_cmpid=@cmpid  
  
      if(isnull(@depart,'')!='')  
      begin  
        INSERT INTO mps_depart(  
          dp_cmpid,  
          dp_bcid,  
          dp_code,  
          dp_depart,  
          dp_order,  
          dp_level,  
          dp_dpstdid  
        )  
        values(@cmpid,  
          @branchid,  
          @code,  
          @depart,  
          @order,  
          @level,  
          @dp_id  
        )  
      end  
    END  
  END  
  
  --删除多余的记录  
  DELETE mps_depart  
  WHERE NOT EXISTS (SELECT dpid FROM @temporary WHERE mps_depart.dp_dpstdid = dpid)  
  AND dp_bcid=@branchid AND dp_cmpid = @cmpid  
  and not exists(select 1 from mps_employee where cu_dpid  = dp_id and cu_bcid = dp_bcid and dp_cmpid = cu_cmpid)  
  
  EXEC mps_update_departinfo @cmpid,@branchid  
END