IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_g_program_tree]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_g_program_tree]
GO
CREATE procedure [dbo].[mps_g_program_tree](
@cmpid int ,
@system int 
) as
begin
set nocount on

insert into mps_programtype(pt_cmpid,pt_caption,pt_program,pt_fid,pt_system,pt_filename,pt_icon,pt_templatename)
select @cmpid , pt_caption,pt_program,pt_fid,pt_system,pt_filename,pt_icon ,pt_templatename
from ebs_kernel.dbo.pub_programtype a 
where not exists (select b.pt_id from mps_programtype b where b.pt_cmpid=@cmpid and a.pt_filename=b.pt_filename) 

-- 计算fid 
declare @t table(fn varchar(50), fid int , ffn varchar(50)) 
insert into @t(fn,fid,ffn) 
select pt_filename , pt_fid , '' from ebs_kernel.dbo.pub_programtype  where pt_fid>0 
update @t set ffn=pt_filename 
from ebs_kernel.dbo.pub_programtype  where  pt_id=fid 

update @t set fid=pt_id
from mps_programtype where pt_cmpid=@cmpid and pt_system<2 and  pt_filename=ffn  

update mps_programtype set pt_fid=fid from @t where pt_cmpid = @cmpid and pt_system<2 and pt_filename=fn  

select * from mps_programtype where  pt_cmpid=@cmpid and  pt_program=1 and pt_system=@system    order by pt_fid, pt_caption 
 set nocount off 
end