Tuesday, 12 August 2014

Csv To StringTable in SQL

CREATE FUNCTION CsvToStringTable(@csvString nvarchar(4000))
RETURNS @stringTable TABLE
                (Value nvarchar(1000))
AS
BEGIN
    DECLARE @separator char(1)
    SET @separator = ','

    DECLARE @separator_position int
    DECLARE @array_value nvarchar(1000)

    SET @csvString = @csvString + ','

    WHILE PATINDEX('%,%', @csvString) <> 0
    BEGIN
        SELECT @separator_position = PATINDEX('%,%', @csvString)
        SELECT @array_value = LEFT(@csvString, @separator_position - 1)

        INSERT @stringTable
        VALUES (RTRIM(LTRIM(Cast(@array_value as nvarchar(1000)))))

        SELECT @csvString = STUFF(@csvString, 1, @separator_position, '')
    END

    RETURN
END