sql - 如何修改json subArray sql server中的特定对象
问题描述
我在 sql db 中有 json 字符串,因为
{
"MainItem":{
"UserId":4,
"UserName":"name",
"CityDetails":{
"CityId":1,
"CityName":"egypt"
},
"ListSubItems":[
{
"UserId":2,
"UserName":"name2",
"FullDescription":"",
"ShortDescription":"wish",
"CityDetails":{
"CityId":2,
"CityName":"us"
}
},
{
"UserId":3,
"UserName":"name3",
"FullDescription":"",
"ShortDescription":"wish",
"CityDetails":{
"CityId":44,
"CityName":"sau"
}
}
]
}
}
您可以在https://jsonparseronline.com/上解析以查看 json
我需要更新$.MainItem.ListSubItems
where UserId=3 set UserName ='new name'
我需要更新所有用户 ID = 3
作为
update MyTable
set jsonCol= json_modify(jsonCol, $.MainItem.ListSubItems .where userId=3 , userName='new name ')
解决方案
如果我遵循您正在尝试做的事情,这应该可以。我不知道您的表中有多少记录,因此可能需要进行一些调整/调整。
DECLARE @MyTable TABLE
(
ID INT IDENTITY (1,1) NOT NULL
,JsonCol NVARCHAR(MAX)
)
INSERT INTO @MyTable
(
JsonCol
)
VALUES
(N'{
"MainItem":{
"UserId":4,
"UserName":"name",
"CityDetails":{
"CityId":1,
"CityName":"egypt"
},
"ListSubItems":[
{
"UserId":2,
"UserName":"name2",
"FullDescription":"",
"ShortDescription":"wish",
"CityDetails":{
"CityId":2,
"CityName":"us"
}
},
{
"UserId":3,
"UserName":"name3",
"FullDescription":"",
"ShortDescription":"wish",
"CityDetails":{
"CityId":44,
"CityName":"sau"
}
}
]
}
}'
)
UPDATE @MyTable
Set JsonCol =
JSON_MODIFY
(jsonCol
,'$.MainItem.ListSubItems'
,(select
orig.UserId
,COALESCE(NewVals.UserName, orig.UserName) as UserName
,orig.FullDescription
,orig.ShortDescription
,orig.CityDetails
from OPENJSON(jsonCol, '$.MainItem.ListSubItems')
WITH (
UserId INT
,UserName NVARCHAR(100)
,FullDescription NVARCHAR(1000)
,ShortDescription NVARCHAR(250)
,CityDetails NVARCHAR(MAX) as json
) as orig
left join
(
SELECT 3 as UserID, 'new name' as UserName
) as NewVals ON orig.UserId = NewVals.UserID
FOR JSON AUTO)
)
SELECT * FROM @MyTable
推荐阅读
- solr - 如何在 SolrCloud 上强制一个领导者?
- python - 熊猫按天分类
- java - 同时选择两个或多个形状
- ios - frame.size 不适合 iphone 模拟器 spritekit swift
- java - 分别用线程 T1 和 T2 打印奇偶数,如果素数来了,则以相反的顺序打印
- javascript - Mongoose:尝试使用 $pullAll 删除引用的对象
- arrays - Swift:从数组中删除特定对象的更好方法?
- android - 无法在列表视图的视频视图中播放视频
- scala - Scala — 有条件地替换数据框的列值
- ruby-on-rails - 使用 Carrierwave 进行 Rails 测试时出现 ArgumentError 异常