我正在寻找一种可以从 SQL Server 中的 JSON 数组中删除元素的方法,我尝试使用 JSON_MODIFY/OPENPATH,但似乎无法正确获取路径参数。
这是我想要做的一个例子是转换:
[{"FieldName":"OrderStatusTypeId","FieldType":"Int32","ValueBefore":"8","ValueAfter":"10","Action":2},{"FieldName":"PatientReferenceNumber","FieldType":"String","ValueBefore":"","ValueAfter":"","Action":2}]
成为:
[{"FieldName":"OrderStatusTypeId","FieldType":"Int32","ValueBefore":"8","ValueAfter":"10","Action":2}]
基本上,我想删除数组的任何元素,其中Action
is 2 和 theValueBefore
和ValueAfter
字段是相同的。
这是我目前正在尝试的测试,但我不断收到以下错误:
DECLARE @JSONData AS NVARCHAR(4000)
SET @JSONData = N'[{"FieldName":"OrderStatusTypeId","FieldType":"Int32","ValueBefore":"8","ValueAfter":"10","Action":2},{"FieldName":"PatientReferenceNumber","FieldType":"String","ValueBefore":"","ValueAfter":"","Action":2},{"FieldName":"PoNumber","FieldType":"String","ValueBefore":"","ValueAfter":"","Action":2},{"FieldName":"ReferringPhysicianName","FieldType":"String","ValueBefore":"","ValueAfter":"","Action":2},{"FieldName":"InsuranceProvider","FieldType":"String","ValueBefore":"","ValueAfter":"","Action":2},{"FieldName":"TreatmentId","FieldType":"String","ValueBefore":"","ValueAfter":"","Action":2},{"FieldName":"RowVersion[6]","FieldType":"Byte","ValueBefore":"10","ValueAfter":"115","Action":2},{"FieldName":"OrderStatusType.Id","FieldType":"Int32","ValueBefore":"8","ValueAfter":"10","Action":2},{"FieldName":"OrderStatusType.Description","FieldType":"String","ValueBefore":"Delivered","ValueAfter":"Failed Logistics","Action":2},{"FieldName":"OrderStatusType.IsSelectable","FieldType":"Boolean","ValueBefore":"False","ValueAfter":"True","Action":2}]'
SELECT @JSONData = JSON_MODIFY(@JSONData, '$',
JSON_QUERY(
(
SELECT *
FROM OPENJSON(@JSONData, '$') WITH (
FieldName nvarchar(1000) '$.FieldName',
FieldType nvarchar(1000) '$.FieldType',
ValueBefore nvarchar(1000) '$.ValueBefore',
ValueAfter nvarchar(1000) '$.ValueAfter',
Action int '$.Action'
)
WHERE Action <> 2 AND ValueBefore <> ValueAfter
FOR JSON PATH
)
)
)
错误:
消息 13619,级别 16,状态 1,第 4 行
JSON_MODIFY 的参数 2 中发现不支持的 JSON 路径。
我正在寻找的预期输出是:
[{"FieldName":"OrderStatusTypeId","FieldType":"Int32","ValueBefore":"8","ValueAfter":"10","Action":2},{"FieldName":"RowVersion[6]","FieldType":"Byte","ValueBefore":"10","ValueAfter":"115","Action":2},{"FieldName":"OrderStatusType.Id","FieldType":"Int32","ValueBefore":"8","ValueAfter":"10","Action":2},{"FieldName":"OrderStatusType.Description","FieldType":"String","ValueBefore":"Delivered","ValueAfter":"Failed Logistics","Action":2},{"FieldName":"OrderStatusType.IsSelectable","FieldType":"Boolean","ValueBefore":"False","ValueAfter":"True","Action":2}]
如何计算出正确的 JSON 路径值,我似乎在网上找到的所有示例都没有数组作为 JSON 字符串的根元素。
请注意,元素的顺序并不重要。