我们有一个表(ms sql azure),其中包含很少的列,其中包含实体的基本详细信息,如下所示:
CREATE TABLE [dbo].[Person]
(
id [uniqueidentifier] NOT NULL,
[firstname] [varchar](50) NULL,
[lastname] [varchar](50) NOT NULL,
[personInfo] [nvarchar](max) NOT NULL,
[createdOn] [datetime] NOT NULL,
[lastUpdateOn] [datetime] NOT NULL,
)
PersonInfo字段具有关于此人的所有其他详细信息的json值,如下所示:
{
"personInfo" : {
"gender" : "string",
"address" : {
"streetAddress" : "string",
"city" : "string",
"district" : "string",
"stateProvince" : "string",
"postalCode" : "string",
"country" : "string",
},
"emailAddress" : "string",
"addlEmails" : [{
"type" : "string",
"address" : "string"
}
],
"businessPhone" : "string",
"mobilePhone" : "string",
"addlPhones" : [{
"type" : "string",
"number" : "string",
"prefix" : "string",
"suffix" : "string"
}
]
}
}
我要求将数据作为JSON从SQL中获取,并将人员信息属性向上移动。如下所示:
{
"id" : "string",
"firstname" : "string",
"lastname" : "string",
"id" : "string",
"gender" : "string",
"address" : {
"streetAddress" : "string",
"city" : "string",
"district" : "string",
"stateProvince" : "string",
"postalCode" : "string",
"country" : "string",
},
"emailAddress" : "string",
"addlEmails" : [{
"type" : "string",
"address" : "string"
}
],
"businessPhone" : "string",
"mobilePhone" : "string",
"addlPhones" : [{
"type" : "string",
"number" : "string",
"prefix" : "string",
"suffix" : "string"
}
]
}
无论如何我能做到这一点吗?
此致 约翰
答案 0 :(得分:2)
没有JSON功能可以"合并"列和JSON或合并两个JSON,因此没有好的和有效的方法来做到这一点。我建议尝试更改外部接口以使用嵌套格式。
如果这是不可能的,这里有一些不那么好的解决方法。
此查询解析personInfo JSON中的某些部分,然后返回与标准列相同的级别,并将它们与json一起格式化:
select id, firstname, lastname, gender, address, emailAddress, addlEmails
from Person
cross apply openjson(personInfo,'$.personInfo')
with ( gender nvarchar(10),
address nvarchar(max) as json,
emailAddress nvarchar(20),
addlEmails nvarchar(max) as json) info
for json path
这种方法创建了两个JSON对象并将它们连接起来,然后用逗号替换} {以合并它们:
select
REPLACE((select id, firstname, lastname for json path, without_array_wrapper) + json_query(personInfo,'$.personInfo'), '}{',',')
from Person