IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_gen_prdctg_power]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_gen_prdctg_power]
GO
create proc [dbo].[mps_gen_prdctg_power]
@cmpid int,
@pcid int,
@pcfather int
as
begin
set nocount on

declare @pcid2 int
declare @ctidf int 
declare @father int


if (@pcfather=0)
begin
declare @forder int,@ftag int
select @forder = pc_order,@ftag = pc_tag from mps_prdctg where pc_id = @pcid
select top 1 @father = pc_id from mps_prdctg
where pc_father = 0 and pc_tag = 0 and pc_order <= @forder and pc_id != @pcid 
order by pc_order desc
end else
begin
set @pcid2 = @pcfather
set @father = @pcfather
--select father pc_id
while (@pcid2>0)
begin
set @ctidf = 0 
select @ctidf = pc_father from mps_prdctg where pc_id=@pcid2 
if (@ctidf>0)
begin
set @pcid2 = @ctidf 
set @father = @ctidf 
end else 
begin
set @pcid2 = 0 
end 
end
end


if(@father>0 and @pcid>0)
begin
declare @count1 int
select @count1 = count(*) from mps_permission
where mp_ctgid = @father and mp_type like 'prd%'

if(@count1>0)
begin
insert into mps_permission(mp_cmpid,mp_type,mp_ctgid,mp_ppid,mp_objid1,mp_objid2,mp_caption,mp_group,mp_order) 
select mp_cmpid,mp_type,@pcid,mp_ppid,mp_objid1,mp_objid2,mp_caption,mp_group,mp_order 
from mps_permission
where mp_ctgid = @father and mp_type like 'prd%'

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

set nocount off
end