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

后端 未结 5 2164
忘掉有多难
忘掉有多难 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:33

    Using Sql Server 2005+ and the XML datatype, you can have a look at the following

    DECLARE @Table TABLE(
            Item VARCHAR(250),
            Colors VARCHAR(250)
    )
    
    INSERT INTO @Table SELECT 'Shirt','Red,Blue,Green,Yellow'
    INSERT INTO @Table SELECT 'Pants','Black,White'
    
    
    ;WITH Vals AS (
            SELECT  Item,
                    CAST('' + REPLACE(Colors, ',', '') + '' AS XML) XmlColumn
            FROM    @Table
    )
    SELECT  Vals.Item,
            C.value('.','varchar(max)') ColumnValue
    FROM    Vals
    CROSS APPLY Vals.XmlColumn.nodes('/d') AS T(C)
    

提交回复
热议问题