How to split string and save into an array in T-SQL

后端 未结 5 2161
忘掉有多难
忘掉有多难 2020-12-19 05:54

I am writing a cursor to populate data in new table from main table which contains data in below manner

Item    Colors
Shirt

5条回答
  •  执念已碎
    2020-12-19 06:20

    The article Faking Arrays in Transact SQL details SEVERAL techniques to solve this problem, ranging from using the PARSENAME() function (limit to 5 items) to writing CLR functions.

    The XML answer is one of the detailed techniques that can be chosen to a specific scenario.

    Combining some of the tips, I solved my string split problem like this:

    SET NOCOUNT ON;
    
    DECLARE @p NVARCHAR(1000), @len INT;
    SET @p = N'value 1,value 2,value 3,value 4,etc';
    SET @p = ',' + @p + ',';
    SET @len = LEN(@p);
    
    -- Remove this table variable creation if you have a permanent enumeration table
    DECLARE @nums TABLE (n int);
    INSERT INTO @nums (n)
        SELECT A.n FROM 
        (SELECT TOP 1000 ROW_NUMBER() OVER (ORDER BY TableKey) as n FROM dbo.Table) A
        WHERE A.n BETWEEN 1 AND @len;
    
    SELECT SUBSTRING(@p , n + 1, CHARINDEX( ',', @p, n + 1 ) - n - 1 ) AS "value"
        FROM @nums
        WHERE SUBSTRING( @p, n, 1 ) = ',' AND n < @len;
    

    Note that, considering 1000 your string length limit, you must have a table with 1000 or more rows (dbo.Table on the sample tsql) to create the table variable @nums of this sample. On the article, they have a permanent enumeration table.

提交回复
热议问题