USE [ArandaDB] GO /****** Object: UserDefinedFunction [dbo].[FN_SUBCATEGORIA_JERARQUIA] Script Date: 05/03/2018 1:53:34 p. m. ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER FUNCTION [dbo].[FN_SUBCATEGORIA_JERARQUIA] (@Arbol_Completo varchar(2000), @Parte_Rama tinyint) RETURNS Varchar(2000) AS BEGIN Declare @Retorno varchar(2000), @Ramas tinyint, @PrimeraPos smallint, @SegundaPos smallint, @MismaPos smallint; if @Parte_Rama > 0 and len(ltrim(rtrim(@Arbol_Completo))) > 0 Begin Set @Ramas = Case @Parte_Rama When 1 then 0 else 1 End; While @Ramas <= (@Parte_Rama - 1) Begin Set @PrimeraPos = Case charindex('.', @Arbol_Completo) When 0 Then 1 Else (charindex('.', @Arbol_Completo) + 1) End; if @Parte_Rama = 1 Begin Set @Retorno = Substring(@Arbol_Completo, 1, Case @PrimeraPos When 1 then len(@Arbol_Completo) Else (@PrimeraPos - 2) End); break; End; Set @SegundaPos = Case charindex('.', Substring(@Arbol_Completo, @PrimeraPos, len(@Arbol_Completo))) When 0 Then len(@Arbol_Completo) Else (charindex('.', Substring(@Arbol_Completo, @PrimeraPos, len(@Arbol_Completo))) - 1) End; Set @Retorno = Substring(@Arbol_Completo, @PrimeraPos, @SegundaPos); if @Retorno = @Arbol_Completo Begin Set @Retorno = ''; break; End; Set @Arbol_Completo = Substring(@Arbol_Completo, @PrimeraPos, len(@Arbol_Completo)); Set @Ramas = @Ramas + 1; Continue; End; End; Else Set @Retorno = ''; RETURN @Retorno; END