




--Creacion Columna
if not exists(select * FROM INFORMATION_SCHEMA.COLUMNS  where Table_Name='ter_sucursal' and column_name = 'id_sucursal' )
begin
alter table [ter_sucursal] add [id_sucursal] int not null default 0
end



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[a_sel_ter_sucursaleshijas]') AND type in (N'P', N'PC'))DROP PROCEDURE [dbo].[a_sel_ter_sucursaleshijas]
GO
Create PROCEDURE [a_sel_ter_sucursaleshijas]
	@p_id INT,
	@campos varchar(500)
AS
BEGIN
DECLARE @valores VARCHAR(5000);
with sucursal_hijos(id,id_sucursal)
AS
(
select id,id_sucursal  from  ter_sucursal 
where ter_sucursal.id=@p_id
union all
select ter_sucursal.id,ter_sucursal.id_sucursal 
 from  ter_sucursal 
 inner join sucursal_hijos on sucursal_hijos.id =ter_sucursal.id_sucursal  
 where ter_sucursal.id_sucursal >0
 )
SELECT @valores= COALESCE(@valores + ',', '') + cast (id as varchar(20)) from sucursal_hijos;
SELECT @valores='id in('+ @valores + ')'
execute [dbo].[sel_ter_sucursales]
@p_filtro=@valores,@p_campos=@campos
END
 