OPENJSON与其他专栏一起扩展

时间:2017-04-19 02:33:32

标签: sql-server json tsql sql-server-2016

我有一个包含

等数据的表格
id     deltas
23     [{"prop1": "value1","prop2": "value2},{"prop1": "value3","prop2": "value4}

这里的想法是增量包含一个对象数组。对象的模式总是prop1和prop2让我们说。这意味着对象将只包含这两个属性。

我所追求的是编写TSQL查询,它提供了类似的内容:

id   property   value
23   prop1      value1
23   prop2      value2
23   prop1      value3
23   prop2      value4

我已经可以使用openjson,因为我将兼容级别设置为130。 我尝试了一个简单的openjson,但它给出的是一个键值,第一个对象为0键,值为json。我想解析该值的JSON。

1 个答案:

答案 0 :(得分:2)

您可以使用OPENJSON从JSON中提取值,然后使用UNPIVOT来重新组织所需格式的值:

--temp table variable that holds your json
declare @source table (id int, props nvarchar(max))
--temp table variable that holds values extracted from your json
declare @tmp table (id int, prop1 nvarchar(max), prop2 nvarchar(max))

--populate temp table with the data you posted
insert into @source
select 23,'[{"prop1": "value1","prop2": "value2"},{"prop1": "value3","prop2": "value4"}]'

--use OPENJSON to extract data from "props" column holding your json
insert into @tmp
select id, prop1,prop2 from  @source  cross apply OPENJSON(props) 
with
(
    prop1 nvarchar(100),
    prop2 nvarchar(100)
)

--unpivot the result to get desired result
select id, u.property, u.value
from  @tmp t
unpivot(
    [value] for [property] in (prop1,prop2)
) u;

以下是此TSQL片段的输出:

enter image description here

如果您不需要中间结果,可以避免使用临时表并一步处理数据:

--temp table variable that holds your json
declare @source table (id int, props nvarchar(max))

--populate temp table with the data you posted
insert into @source
select 23,'[{"prop1": "value1","prop2": "value2"},{"prop1": "value3","prop2": "value4"}]'

--use openjson to fetch data from JSON and then unpivot the result to get desired format
select id, u.property, u.value
from  (select id, prop1, prop2 from  @source  cross apply OPENJSON(props) 
with
(
    prop1 nvarchar(100),
    prop2 nvarchar(100)
)
) t
unpivot(
    [value] for [property] in (t.prop1,t.prop2)
) u;

<强> P.S。

您发布的JSON:

[{"prop1": "value1","prop2": "value2},{"prop1": "value3","prop2": "value4}

无效,因为在 value2 value4 之后缺少最后的方括号和几个引号。你可以使用ISJSON()来检查这一点,它将返回0:

select isjson(' [{"prop1": "value1","prop2": "value2},{"prop1": "value3","prop2": "value4}')

所以我假设输入实际上是:

[{"prop1": "value1","prop2": "value2"},{"prop1": "value3","prop2": "value4"}]