Nem*_*emo 0 sql t-sql sql-server
在T-SQL中如何将一列分开;一个带有键,另一个带有遵循以下模式的字符串的值?
需要处理的字符串示例有:
示例 1 的预期结果是:
| 钥匙 | 价值 |
|---|---|
| 国家代码 | 我们 |
| 省份名称 | 纽约 |
| 城市名 | 老查塔姆 |
很高兴见到老查塔姆......有点家的感觉
我的第一个想法是“更正”JSON 字符串,但这有风险。
这是一个将解析和配对键/值的选项
示例或dbFiddle
Select A.*
,C.*
From YourTable A
Cross Apply ( values ( replace(replace(replace(SomeCol,'"',':'),': :',':'),'::',':') ) ) B(CleanString)
Cross Apply (
Select [Key] =max(case when Seq=1 then Val end)
,[Value]=max(case when Seq=0 then Val end)
From (
Select Seq = row_number() over (order by [Key]) % 2
,Grp = (row_number() over (order by [Key])-1) / 2
,Val = Value
From OpenJSON( '["'+replace(string_escape(CleanString,'json'),':','","')+'"]' )
Where ltrim(Value)<>''
) C1
Group By Grp
) C
Run Code Online (Sandbox Code Playgroud)
结果