IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_save_depart_base]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_save_depart_base]
GO
CREATE PROCEDURE [dbo].[mps_save_depart_base]
  @cmpid int,
  @dp_id int,
  @dp_code varchar(20),
  @dp_depart nvarchar(50),
  @order bigint
AS
 BEGIN
  SET NOCOUNT ON;

  declare @effect int = 0

  UPDATE mps_depart_base
  SET
    dp_code = CASE WHEN @dp_code = '_none_' THEN dp_code ELSE @dp_code END,
    dp_order = CASE WHEN @order = -999999999999 THEN dp_order ELSE @order END,
    dp_depart = CASE WHEN @dp_depart = '_none_' THEN dp_depart ELSE @dp_depart END
  WHERE dp_id = @dp_id
  AND dp_cmpid = @cmpid

  update mps_employee
  set cu_depart = src.dp_depart
  from mps_depart dp with(nolock)  ,
    mps_depart_base src with(nolock)
  where dp.dp_dpstdid = src.dp_id
  and src.dp_id = @dp_id
  and dp.dp_id = cu_dpid
  and dp.dp_bcid = cu_bcid

  update mps_login
  set cu_depart = src.dp_depart
  from mps_depart dp with(nolock)  ,
    mps_depart_base src with(nolock)
  where dp.dp_dpstdid = src.dp_id
  and src.dp_id = @dp_id
  and dp.dp_id = cu_dpid
  and dp.dp_bcid = cu_bcid

  update mps_login_role
  set lgu_depart = src.dp_depart
  from mps_depart dp with(nolock)  ,
    mps_depart_base src with(nolock)
  where dp.dp_dpstdid = src.dp_id
  and src.dp_id = @dp_id
  and dp.dp_id = lgu_dpid
  and dp.dp_bcid = lgu_bcid

  update tar
  set
    tar.dp_depart = src.dp_depart,
    tar.dp_order = src.dp_order,
    tar.dp_level = src.dp_level,
    tar.dp_fullname = src.dp_depart,
    tar.dp_display = src.dp_depart
  from  mps_depart tar,mps_depart_base src
  where src.dp_id = tar.dp_dpstdid
  and src.dp_cmpid = tar.dp_cmpid
  and @dp_id  = src.dp_id

  set @effect = @@ROWCOUNT

  select @effect result

END