分离出键值对

Nem*_*emo 0 sql t-sql sql-server

在T-SQL中如何将一列分开;一个带有键,另一个带有遵循以下模式的字符串的值?

需要处理的字符串示例有:

  1. Country_code:“US”province_name:“NY”city_name:“Old Chatham”
  2. 邮政编码:“11746-8031”国家/地区代码:“美国”省名:“纽约”街道地址:“151 米勒街北”城市名称:“迪克斯山”
  3. street_address:“1036 Main Street,霍尔布鲁克,NY 11741”

示例 1 的预期结果是:

钥匙 价值
国家代码 我们
省份名称 纽约
城市名 老查塔姆

Joh*_*tti 5

很高兴见到老查塔姆......有点家的感觉

我的第一个想法是“更正”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)

结果

在此输入图像描述