逗号分隔的字符串
Comma-delimited string
使用 T-SQL,我有一个像这样的逗号分隔字符串
'Value1,Value2,"Value3,Value4,Value5",Value6'
我想将它放入这样的数组中:
Array[0] = 'Value1'
Array[1] = 'Value2'
Array[2] = 'Value3,Value4,Value5'
Array[3] = 'Value6'
感谢任何帮助!谢谢!
这个方法有点绕
但它可以将字符串转换为 JSON 数组的格式。
然后在上面使用JSON functions会更容易。
该示例使用接受模式的 UDF fnPattern_Split
来取消嵌套字符串。
可以找到源代码
declare @str varchar(max), @js varchar(max);
set @str ='Value1,Value2,"Value3,Value4,Value5",Value6';
;with cte1 as (
select *
from dbo.fnPattern_Split(@str,'"%"') ps
)
, cte2 as (
select ordinal as ord1, 0 as ord2, value
from cte1
where match = 1
union all
select c.ordinal, ps.ordinal, quotename(ps.value,'"') as value
from cte1 c
cross apply fnPattern_Split(c.value,',') ps
where c.match = 0 and ps.match = 0
)
select @js = '['+string_agg(value, ',')
within group (order by ord1, ord2)+']'
from cte2;
print(@js);
select *
from OPENJSON(@js) js;
key
value
type
0
Value1
1
1
Value2
1
2
Value3,Value4,Value5
1
3
Value6
1
在 db<>fiddle here
上测试
使用 T-SQL,我有一个像这样的逗号分隔字符串
'Value1,Value2,"Value3,Value4,Value5",Value6'
我想将它放入这样的数组中:
Array[0] = 'Value1'
Array[1] = 'Value2'
Array[2] = 'Value3,Value4,Value5'
Array[3] = 'Value6'
感谢任何帮助!谢谢!
这个方法有点绕
但它可以将字符串转换为 JSON 数组的格式。
然后在上面使用JSON functions会更容易。
该示例使用接受模式的 UDF fnPattern_Split
来取消嵌套字符串。
可以找到源代码
declare @str varchar(max), @js varchar(max); set @str ='Value1,Value2,"Value3,Value4,Value5",Value6'; ;with cte1 as ( select * from dbo.fnPattern_Split(@str,'"%"') ps ) , cte2 as ( select ordinal as ord1, 0 as ord2, value from cte1 where match = 1 union all select c.ordinal, ps.ordinal, quotename(ps.value,'"') as value from cte1 c cross apply fnPattern_Split(c.value,',') ps where c.match = 0 and ps.match = 0 ) select @js = '['+string_agg(value, ',') within group (order by ord1, ord2)+']' from cte2; print(@js); select * from OPENJSON(@js) js;
key | value | type |
---|---|---|
0 | Value1 | 1 |
1 | Value2 | 1 |
2 | Value3,Value4,Value5 | 1 |
3 | Value6 | 1 |
在 db<>fiddle here
上测试