IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_save_permission]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_save_permission]
GO
create procedure [dbo].[mps_save_permission] 
@cmpid int ,
@mdtype varchar(20),
@ctgid int,
@group int , 
@value varchar(50),
@caption nvarchar(100),
@byorder int 
as 
begin
declare @ppid int 
declare @objid int 
declare @objid2 int 
declare @s1 varchar(50) 
declare @s2 varchar(50) 
declare @i int 
set @s1 = @value 
set @i = charindex(',',@s1) 
set @s2 = substring(@s1,1,@i-1) 
set @s1 = substring(@s1,@i+1,len(@s1)-@i) 
set @ppid = convert(int,@s2) 
set @i = charindex(',',@s1) 
set @s2 = substring(@s1,1,@i-1) 
set @s1 = substring(@s1,@i+1,len(@s1)-@i) 
set @objid = convert(int,@s2) 
set @objid2 = convert(int,@s1) 

declare @mp_id int 
select top 1 @mp_id=mp_id from mps_permission where mp_cmpid=@cmpid and mp_type=@mdtype and mp_ctgid=@ctgid 
and mp_ppid=@ppid and mp_objid1=@objid and mp_objid2=@objid2  and mp_group=@group 
set @mp_id=isnull(@mp_id,0) 
if (@mp_id=0)
begin
insert into mps_permission(mp_cmpid,mp_type,mp_ctgid,mp_ppid,mp_objid1,mp_objid2,mp_caption,mp_group,mp_order) 
values(@cmpid,@mdtype ,@ctgid , @ppid , @objid, @objid2,@caption,@group,@byorder) 

if (@mdtype like 'prd%' and @ctgid >0)
begin
exec mps_up_prdctg_power @cmpid,@ctgid,@mdtype,@ppid,'insert'
end
end  else 
begin
update mps_permission set mp_caption=@caption,mp_order=@byorder where mp_id=@mp_id 

declare @mptype varchar(255), @mpctgid int
select top 1 @mptype=mp_type,@mpctgid = mp_ctgid,@ppid = mp_ppid from  mps_permission 
where mp_id = @mp_id

if (@mptype like 'prd%' and @mpctgid >0)
begin
exec mps_up_prdctg_power @cmpid,@mpctgid,@mptype,@ppid,'update'
end
end 

update mps_biztype set biz_changed = 0  where @mdtype like 'biz%' and @ctgid=biz_id 

update mps_flowwork set wrk_changed = 0 where @mdtype like 'wrk%' and @ctgid=wrk_id 

update mps_docctg set dc_changed = 0 where @mdtype like 'doc%' and @ctgid=dc_id 

update mps_prdctg set pc_changed = 0 where @mdtype like 'prd%' and @ctgid=pc_id 

update mps_equctg set ec_changed = 0 where @mdtype like 'equ%' and @ctgid=ec_id 

update mps_csttype set ct_changed = 0 where @mdtype like 'cst%' and @ctgid=ct_id 

update mps_ext_resource set etc_changed = 0 where @mdtype like 'etc%' and @ctgid=etc_id 

update mps_programtype set pt_changed = 0 where @mdtype like 'etc%' and @ctgid=pt_id 
end