fjtello / SQL-C-sharp

Common programming and coding tips and howtos
0 stars 0 forks source link

SQL Syntax [#split] #24

Open fjtello opened 7 years ago

fjtello commented 7 years ago

SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ================================================================ -- Creación: 2017.04.07 -- Descripción: Crear tabla a partir de cadena de texto -- ================================================================ ALTER FUNCTION fncSplit (
@cadena VARCHAR(MAX) = NULL, @separador VARCHAR(5) = NULL ) RETURNS @t TABLE ( valor VARCHAR(50) ) AS BEGIN DECLARE @a AS VARCHAR(MAX); SET @a = @cadena; BEGIN IF(RTRIM(ISNULL(@separador, '')) = '') SET @separador = ';';

    SET @a = REPLACE(REPLACE(@a, CHAR(13), @separador), CHAR(10), @separador);

    DECLARE @inner AS VARCHAR(50); 
    DECLARE @posicion AS INT;

    SET @a = @a + @separador;

    WHILE(CHARINDEX(@separador + @separador, @a)>0) 
        SET @a = REPLACE(@a, @separador + @separador, @separador);

    WHILE(CHARINDEX(@separador, @a)>0)
    BEGIN

        SET @posicion = CHARINDEX(@separador, @a);
        SET @inner = RTRIM(LTRIM(SUBSTRING(@a, 1, @posicion - 1)));

        IF(@inner <> '') 
            BEGIN
                IF(0=(SELECT COUNT(*) FROM @t WHERE valor = @inner))
                    INSERT INTO @t (valor) VALUES (@inner);
            END

        SET @a = SUBSTRING(@a, @posicion + 1, LEN(@a) - @posicion);

    END

END

RETURN      

END GO