good-arrow’s blog

https://good-arrow.net/

【stored function】CSV to Table

This stored function converts a CSV to Table, for SQL Server.

Function:sf_Csv2Table(text, separator, nulltext)

text : The text to be split.
separator : The text delimiter by which the text will be separated.
nulltext : Value to be converted to NULL.

CREATE FUNCTION dbo.sf_Csv2Table (
    @Texts as nvarchar(max),
    @SeparatorChar as char(1) = ',',
    @NullText as nvarchar(16) = '<NULL>'
)
RETURNS @Table TABLE([DATA] int) AS
BEGIN


    DECLARE @Cnt int;
    DECLARE @NextChar nvarchar(1);
    DECLARE @SaveText nvarchar(max);
    SELECT @Cnt = 1, @NextChar = '', @SaveText = '';

    WHILE @Cnt <= LEN(@Texts)
    BEGIN

        SET @NextChar = SUBSTRING(@Texts, @Cnt, 1);

        IF @NextChar = @SeparatorChar
        BEGIN
            IF @SaveText = @NullText SELECT @SaveText = null;
            INSERT INTO @Table VALUES(@SaveText);
            SELECT @SaveText = '';
        END

        IF @NextChar <> @SeparatorChar 
            SELECT @SaveText = @SaveText + SUBSTRING(@Texts, @Cnt, 1);

        SET @Cnt = @Cnt + 1;

    END

    IF @SaveText = @NullText SELECT @SaveText = null;
    INSERT INTO @Table VALUES( CAST(@SaveText as int) );

    RETURN

END