sql-server - 从字符串中提取子字符串并在 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"}
我正在尝试一个结合子字符串和替换的函数,但它对我不起作用。
解决方案
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
;
推荐阅读
- python - 动态创建列表(即时)
- spring-cloud - 尽管启用了机制,Zuul 不会重试失败的请求
- python - 如何按名称编辑列
- python - 如何使用请求在 Python 中发布多部分/表单数据
- altium-designer - 如何在 Altium 中移动工作表边框并与网格对齐
- r - 用于在 R 中的数据框中计算和添加新列的函数
- micrometer - MicroMeter LongTaskTimer如何在方法失败时清除样本
- java - Spring Boot 如何找到控制器包?
- ttl - 如何确定 VaultClient 获取的 Vault 令牌的 TTL
- tableau-api - 您如何将不同年份的数据放在同一张图表上?