SQL server如何列表里将逗号分隔的字符串进行分拆成多行
时间: 2023-05-26 15:07:16 浏览: 97
oracle将以逗号分隔字符串转多行
在SQL Server中,可以使用以下方法将逗号分隔的字符串拆分成多行:
方法1:使用XML
```
DECLARE @str VARCHAR(100) = 'apple,orange,banana,mango'
SELECT
Split.a.value('.', 'VARCHAR(100)') AS Fruit
FROM
(SELECT
CAST ('<M>' + REPLACE(@str, ',', '</M><M>') + '</M>' AS XML) AS Data
) AS A
CROSS APPLY Data.nodes ('/M') AS Split(a)
```
方法2:使用字符串函数
```
DECLARE @str VARCHAR(100) = 'apple,orange,banana,mango'
;WITH temp AS
(
SELECT CAST('<M>' + REPLACE(@str, ',', '</M><M>') + '</M>' AS XML) AS FruitList
)
SELECT
Fruit.value('.', 'VARCHAR(100)') AS Fruit
FROM
temp CROSS APPLY
FruitList.nodes('/M') AS Fruit(Fruit)
```
这两种方法都将逗号分隔的字符串转换为XML格式,并使用XML的属性来拆分每个值。然后使用CROSS APPLY或节点函数将拆分后的值转换为多行结果。
阅读全文