Sqlserver
 sql >> Base de données >  >> RDS >> Sqlserver

Fractionnement des valeurs délimitées dans une colonne SQL en plusieurs lignes utilisant plusieurs délimiteurs

Essayez ceci :

Basé sur l'article de ici

;with T(id, Cols) as
(
  select 1, '10 x 1234 description1,11 x 456 description2' 
  UNION ALL
  select 2, '40 x 123478 description3,51 x 45678 description4' 
),
--first split all comma separated into different rows
CTE2 AS 
(
    SELECT id, 
    CAST(N'<H><r>' + replace(Replace(Vals.a.value('.', 'NVARCHAR(50)'),
        ' ','|'), '|', '</r><r>') + '</r></H>' as XML) Cols
    FROM
    (
    SELECT *,CAST (N'<H><r>' + Replace(cols,',','</r><r>') + 
        '</r></H>' AS XML) AS [vals]
    FROM T) d
    CROSS APPLY d.[vals].nodes('/H/r') Vals(a)
)
-- split all ' ' demilited values now
SELECT distinct id, Vals.a.value('(/H/r)[1]', 'VARCHAR(100)') AS Qty,
Vals.a.value('(/H/r)[2]', 'VARCHAR(100)') AS X,
Vals.a.value('(/H/r)[3]', 'VARCHAR(100)') AS ItemNo,
Vals.a.value('(/H/r)[4]', 'VARCHAR(100)') AS Description
FROM
(
SELECT *
FROM CTE2) d
CROSS APPLY d.[cols].nodes('/H/r') Vals(a)