使用 T-SQL,我有一個像這樣的逗號分隔字串
'Value1,Value2,"Value3,Value4,Value5",Value6'
我想把它放到這樣的陣列中:
Array[0] = 'Value1'
Array[1] = 'Value2'
Array[2] = 'Value3,Value4,Value5'
Array[3] = 'Value6'
任何幫助表示贊賞!謝謝!
uj5u.com熱心網友回復:
這是一個有點復雜的方法。
但它可以將字串轉換為 JSON 陣列的格式。然后在上面使用JSON 函式
會更容易。
該示例使用fnPattern_Split接受模式的 UDF 來取消對字串的嵌套。
源代碼可以在這里找到
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;
| 鑰匙 | 價值 | 型別 |
|---|---|---|
| 0 | 價值1 | 1 |
| 1 | 價值2 | 1 |
| 2 | 值 3、值 4、值 5 | 1 |
| 3 | 價值6 | 1 |
在這里測驗db<>fiddle
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/435009.html
