2017-06-07 7 views
1

json列を持つ表があり、jsonには項目の配列が含まれています。特定の基準が満たされているアイテムの一部を更新したいと思います。したがって、配列へのパスは$.activitiesであり、typeは 'multichoice i want to set 'data.insightsTitledata.title'です。JSON_MODIFYを使用して、配列の一部の条件に一致するすべての要素を更新する方法

私はちょっと頭を傷つけていたので、パスを検索するのはとにかく(良いol 'xpathのように)思われません。

答えて

1

私はこの解決策を思いついた、うまくいくと思われ、あまりにも総体ではありません!これは、一致する各配列項目のjson列に書き込むときにループを必要とします。

begin tran t1 

DECLARE @Count int = -1 

while @Count != 0 
begin 
update dp 
    set definition = JSON_MODIFY(dp.definition, '$.activities[' + (CAST(src.[key] as nvarchar(6)) COLLATE SQL_Latin1_General_CP1_CI_AS) + ']', JSON_MODIFY(src.value, '$.data.insightsTitle', JSON_VALUE(src.value, '$.data.title'))) 
from 
    deviceprofile dp 
join (
select dp.deviceprofileid, g.*--dp.definition 
from deviceprofile dp 
CROSS APPLY OPENJSON(dp.definition, '$.activities') g 
) src on dp.deviceprofileid = src.deviceprofileid 
where JSON_VALUE(src.value, '$.type') = 'multichoice' and JSON_VALUE(src.value, '$.data.insightsTitle') is null 

select @count = count(distinct dp.deviceprofileid) 
from deviceprofile dp 
CROSS APPLY OPENJSON(dp.definition, '$.activities') WITH (type nvarchar(100), insightsTitle nvarchar(256) '$.data.insightsTitle') g 
where g.type = 'multichoice' and g.insightsTitle is null 

print @count 
end 

rollback tran 

ですから、WITHを指定いけない場合、あなたはあなたのインデックスと配列項目の完全なJSONを与え、この魔法Key列を取得します。そのブロックとその使用方法を更新して、一致する配列項目ごとにjson文字列全体を1つずつ更新します。楽しい。

関連する問題