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

CREATE PROCEDURE [dbo].[g_weixin_navigationmenus]    
 @cmpid int ,    
 @roleid int,    
 @stateid int    
AS    
BEGIN    
 -- SET NOCOUNT ON added to prevent extra result sets from    
 -- interfering with SELECT statements.    
 SET NOCOUNT ON;    
 --先将满足条件的放入临时表    
 declare @count int = 0
 declare @temp table(id int)    
 insert into @temp  select A.mn_id from mps_menu A where (mn_cmpid=@cmpid and mn_flag='head_state'+CONVERT(char,@stateid) and mn_terminal=1 and mn_roleid=@roleid)     
 select @count = count(*) from @temp
 if(@count=0)
 insert into @temp  select A.mn_id from mps_menu A where (mn_cmpid=@cmpid and mn_flag='head_state'+CONVERT(char,@stateid) and mn_terminal=1 and mn_roleid=0)     
 --从中选取满足条件的一级菜单    
 select B.* ,(select count(*) from mps_menu C where C.mn_flag='head_sub'+CONVERT(char,A.id)) mn_subcount    
 from  @temp A,mps_menu B    
 where A.id=B.mn_id    
 order by B.mn_order  
 --从中选取满足条件的二级菜单    
 select B.*     
 from  @temp A,mps_menu B    
 where b.mn_flag='head_sub'+CONVERT(char,A.id)  
 order by B.mn_order  
END