code-tutorial.com

The best resources for developers

How do I divide a string so I can access item x?

Declare @products varchar(200) = "1|20|3|343|44|6|8765"
Declare @individual varchar(20) = null

WHILE LEN(@products) > 0
BEGIN
    IF PATINDEX("%|%", @products) > 0
    BEGIN
        SET @individual = SUBSTRING(@products,
                                    0,
                                    PATINDEX("%|%", @products))
        SELECT @individual

        SET @products = SUBSTRING(@products,
                                  LEN(@individual + "|") + 1,
                                  LEN(@products))
    END
    ELSE
    BEGIN
        SET @individual = @products
        SET @products = NULL
        SELECT @individual
    END
END

Tags: sql tsql sql-server split

Source: By GateKiller as answer to the question

This code snippet was collected from stackoverflow, and is licensed under CC BY-SA 3.0


Related code-snippets: