Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Delimited string to table
CREATE FUNCTION [dbo].[DelimitedStringToTable]
(
        @String nvarchar(MAX),
        @Delimiter nvarchar(1)
)
RETURNS @Items TABLE
(
        Item nvarchar(50)
)
AS
BEGIN
        DECLARE @Item nvarchar(50)
        DECLARE @Pos INT
        DECLARE @NextPos        INT
        SET @Pos = 1
        WHILE(@Pos <= LEN(@String))
        BEGIN
                SELECT @NextPos = CHARINDEX(@Delimiter, @String,  @Pos)
                IF (@NextPos = 0 OR @NextPos IS NULL)
                        SELECT @NextPos = LEN(@String) + 1
                SELECT @item = RTRIM(LTRIM(SUBSTRING(@String, @Pos, @NextPos - @Pos)))
                SELECT @Pos = @NextPos+1
                INSERT INTO @Items VALUES (@Item)
        END
        RETURN
END
GO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.