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

CREATE proc [dbo].[mps_new_depart_shop] 
@mybcid int,
@cmpid int,
@branchid int,
@userdpid int,
@useruid int,
@userotid int
as
begin
set nocount on
declare @operation varchar(50)
declare @errorinfo nvarchar(4000) 

declare @dpid bigint
set @dpid = 0;
select @dpid = dp_id from mps_depart where dp_cmpid = @cmpid and dp_bcid = @mybcid and dp_code = '' and dp_isdepart = 1
if @dpid = 0 
begin
insert into mps_depart(dp_cmpid,dp_bcid,dp_code,dp_dpstdid,dp_order,dp_isdepart) values(@cmpid,@mybcid,'',@dpid,999,1);
select top 1 @dpid = dp_id from mps_depart 
where dp_cmpid =@cmpid and dp_bcid = @mybcid and  dp_code = ''
and dp_dpstdid = @dpid and dp_order = 999 and dp_isdepart = 1
order by dp_id desc
end 
if (dbo.mps_sys_checkkeywords('shp.beforecreate,shp.aftercreate',@cmpid,0,'','')=0)   -- 有事件
begin
exec drop_temp_table '#old'
select * into #old from mps_depart where dp_id = @dpid
exec drop_temp_table '#new'
select *  into #new from #old 
end
--门店新建之前
if (dbo.mps_sys_checkkeywords('shp.beforecreate',@cmpid,0,'','')=0) 
begin
exec mps_depart_newshp_before @cmpid,@branchid,@userdpid,@useruid,@userotid,@dpid,@operation output,@errorinfo output
if @operation = 'abort' 
begin
delete from mps_depart where dp_id = @dpid
select @operation operation,@errorinfo errorinfo
return 
end
end

if @dpid >0 select @dpid as dp_id
else select 0 as dp_id
--部门新建之后
if (dbo.mps_sys_checkkeywords('shp.aftercreate',@cmpid,0,'','')=0) 
begin
exec mps_depart_newshp_after @cmpid,@branchid,@userdpid,@useruid,@userotid,@dpid
end


set nocount off
end