首页 > 解决方案 > 从字符串中提取子字符串并在 SQL Server 中替换

问题描述

我有一eventDescription列包含以下字符串:

Event info: code exchange. Response: {"access_code":"asdewsderfgtyhujikhygtrfdesaqwer","refresh_code":"asdewsderfgtyhujikhygtrfdesaqwer"}

我需要替换并为代码加上一个掩码,如下所示:

Event info: code exchange. Response: {"access_code":"asdewsderfgtyhujikhygtrfdeXXXXX","refresh_code":"asdewsderfgtyhujikhygtrfdesXXXXX"}

我正在尝试一个结合子字符串和替换的函数,但它对我不起作用。

标签: sql-serverreplacesetsubstring

解决方案


cross apply, json_value,json_modify是你的朋友吗:

update tgt
set eventDescription = evt.pfx
                     + json_modify(json_modify(evt.jsn
                      ,'$.access_code' ,jsn.acc+'XXXXX') -- apply whatever transformation(s)
                      ,'$.refresh_code',jsn.ref+'XXXXX') -- you need to the values
from TheTable tgt

     -- find position that divides the prefix from the json
     cross apply (select charindex('{',tgt.eventDescription)-1) div(pos)

     -- use the above value to split into prefix and json
     cross apply (
    select left(tgt.eventDescription,div.pos)
          ,stuff(tgt.eventDescription,1,div.pos,'')) evt(pfx,jsn)

     -- get values for the two json attributes
     cross apply (
    select json_value(evt.jsn,'$.access_code')
          ,json_value(evt.jsn,'$.refresh_code')) jsn(acc,ref)

where tgt.eventDescription like '%{%'  -- only for rows matching the pattern
  and isjson(evt.jsn) = 1              -- and have valid json
;

推荐阅读