将多余的条目移到SQL Server中的新行

时间:2018-07-04 13:42:02

标签: sql sql-server

我有一张桌子。


Country|  Continent|  City
----------------------------
USA      Americas   [{1,New York}]
Chile    Americas   [{2,Santiago}]
England  Europe     [{3,London},{4,Bristol}]

我想将多余的条目移到sql server中的新行。输出需要看起来像这样。

----------------------------
Country|  Continent|  City
----------------------------
USA      Americas   [{1,New York}]
Chile    Americas   [{2,Santiago}]
England  Europe     [{3,London}]
England  Europe     [{4,Bristol}]

1 个答案:

答案 0 :(得分:2)

尝试一下

;WITH CTE(Country,  Continent,  City)
AS
(
SELECT 'USA'    ,'Americas' ,'[{1,New York}]'   UNION ALL
SELECT 'Chile'  ,'Americas' ,'[{2,Santiago}]'   UNION ALL
SELECT 'England','Europe'   ,'[{3,London},{4,Bristol}]'
)
SELECT  Country,
        Continent,
        QUOTENAME(IIF(RIGHT(Split.a.value('.','nvarchar(1000)'),1)<>'}',Split.a.value('.','nvarchar(1000)')+'}' ,Split.a.value('.','nvarchar(1000)')))
AS City
FROM
(
SELECT Country,Continent,CAST('<S>'+ REPLACE(REPLACE(REPLACE(City,'[',''),']',''),'},','</S><S>' )+'</S>' AS XML) AS City
FROM CTE
)AS A
CROSS APPLY City.nodes('S') AS Split(a)

演示结果:http://rextester.com/AWWN39720