我有一个如下所示的 JSON 字符串:
[{'tagType': 'Author', 'tagValue': 'Anne Author'}, {'tagType': 'Business', 'tagValue': 'the bidness'}, {'tagType': 'Geography', 'tagValue': 'US'}, {'tagType': 'Subscription', 'tagValue': 'A subscription'}]
对于给定的 tagType(例如地理),如何获取 tagValue(例如 US)
我尝试过各种丑陋的选择查询。我觉得必须有一种优雅的方式来做到这一点
此查询(作为更大查询的一部分)有效
[Geography] = (SELECT tagValue
FROM OPENJSON(REPLACE(p.tags, '''', '"'))
WITH (tagType VARCHAR(255) '$.tagType', tagValue VARCHAR(255) '$.tagValue')
WHERE tagType = 'Geography')
Openjson 几乎正确
declare @j nvarchar(max)= N'[{"tagType": "Author", "tagValue": "Anne Author"}, {"tagType": "Business", "tagValue": "the bidness"}, {"tagType": "Geography", "tagValue": "US"}, {"tagType": "Subscription", "tagValue": "A subscription"}]'
select *
from OPENJSON(@j)
WITH (
tagType varchar(20),
tagValue varchar(20)
)
结果:
标签类型 | 标签值 |
---|---|
作者 | 安妮作者 |
商业 | 出价 |
地理 | 美国 |
订阅 | 订阅 |