IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_up_prdctg_power]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_up_prdctg_power]
GO
create proc [dbo].[mps_up_prdctg_power]
@cmpid int,
@pcid int,
@mptype varchar(255),
@ppid int,
@optype varchar(50)
as
begin
set nocount on
declare  @caption nvarchar(255), @mporder int
declare @mp_objid1 int, @mp_group int, @mp_objid2 int


if(@optype = 'delete') -- delete permission
begin
declare @prdctg11 table(nid int identity(1, 1),pcid int) 
if @mptype not like 'prd%' return
-- insert pc_id
insert into @prdctg11(pcid)
select pc_id from mps_prdctg 
where pc_ffpcid = @pcid

delete mps_permission
from @prdctg11 
where mp_type = @mptype and mp_ctgid = pcid and mp_ppid = @ppid

end else
if(@optype = 'update') --update permission
begin
declare @prdctg22 table(mp_type varchar(255),mp_ctgid int,mp_ppid int,mp_caption nvarchar(255),mp_order int)
select @caption = mp_caption, @mporder = mp_order
from mps_permission where mp_ctgid = @pcid and mp_type = @mptype and mp_ppid = @ppid
-- insert data   
insert into @prdctg22(mp_type,mp_ctgid,mp_ppid,mp_caption,mp_order) 
select @mptype,pc_id,@ppid,@caption,@mporder from mps_prdctg 
where pc_ffpcid = @pcid
-- now update permission
update mps_permission 
set mp_caption=a.mp_caption, mp_order=a.mp_order  
from @prdctg22  a
where mps_permission.mp_type=a.mp_type and mps_permission.mp_ctgid=a.mp_ctgid and mps_permission.mp_cmpid = @cmpid and mps_permission.mp_ppid = @ppid
end else
if(@optype = 'insert')
begin
select @caption = mp_caption, @mporder = mp_order,@mp_objid1=mp_objid1 , @mp_group=mp_group, @mp_objid2 = mp_objid2
from mps_permission where mp_ctgid = @pcid and mp_type = @mptype and mp_ppid = @ppid

-- now insert permission
insert into mps_permission(mp_cmpid,mp_type,mp_ctgid,mp_ppid,mp_objid1,mp_objid2,mp_caption,mp_group,mp_order) 
select @cmpid,@mptype,pc_id,@ppid,@mp_objid1,@mp_objid2,@caption,@mp_group,@mporder 
from mps_prdctg 
where pc_ffpcid = @pcid

update  mps_prdctg set pc_changed =0 where pc_id = @pcid
end

update mps_prdctg set pc_changed = 0 
where pc_ffpcid = @pcid

set nocount off
end