IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_delete_depart_base]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_delete_depart_base]
GO


CREATE procedure [dbo].[mps_delete_depart_base]
 -- Add the parameters for the stored procedure here
 @cmpid int,
 @dp_id int
AS
BEGIN
 -- SET NOCOUNT ON added to prevent extra result sets from
 -- interfering with SELECT statements.
 SET NOCOUNT ON;

    -- Insert statements for procedure here
 if not exists(select * from
     mps_login_role ro with(nolock),
     mps_depart_base dpt with(nolock),
     mps_depart dp with(nolock)
    where dpt.dp_id = dp.dp_dpstdid
    and dp.dp_id = ro.lgu_dpid
    and dpt.dp_id = @dp_id
    ) and
  not exists(select * from
     mps_employee emp with(nolock),
     mps_depart_base dpt with(nolock),
     mps_depart dp with(nolock)
    where dpt.dp_id = dp.dp_dpstdid
    and dp.dp_id = emp.cu_dpid
    and dpt.dp_id = @dp_id
    )
 begin

   DELETE mps_depart_base WHERE dp_cmpid = @cmpid AND dp_id = @dp_id
   DELETE mps_depart WHERE dp_dpstdid = @dp_id

   select 'ok' result
 end
 else
  select 'error' result

END