SET ANSI_NULLS OFF
SET QUOTED_IDENTIFIER OFF
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sel_gen_zona_zonas]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sel_gen_zona_zonas]
GO
CREATE PROCEDURE [dbo].[sel_gen_zona_zonas]
	@p_filtro as varchar (8000) = '1=1',
	@p_orden as varchar (8000) = 'id',
	@p_campos as varchar (8000) = '*',
    @p_filtro_id as varchar(8000)='id=(select max(id) from gen_zona where nivel=(select max(nivel) from gen_zona) )'
 AS
BEGIN
exec ('SELECT '+ @p_campos +
' FROM [view_gen_zona]
WHERE   (' + @p_filtro + ') and nivel <=(SELECT nivel
 FROM [view_gen_zona]
WHERE  ( '+@p_filtro_id+')group by nivel) and not id_zona =(SELECT id
 FROM [view_gen_zona]
WHERE  ('+@p_filtro_id+')group by id) ORDER BY ' + @p_orden)
END
GO
