2017-05-31 63 views
0

我們正處於一個表(MS SQL Azure的)與具有實體的基本細節,如下面幾列:移動JSON最多的層次

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" 
      } 
     ] 
    } 
} 

我有一個要求獲取數據了從SQL與個人信息一個JSON的水平屬性上升。像如下:

{ 
    "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" 
     } 
    ] 
} 

有反正我可以做到這一點嗎?

問候, 約翰

回答

2

沒有JSON功能,可以「合併」列和JSON或合併兩個JSONs,所以沒有很好的和有效的方式來做到這一點。我會建議嘗試更改外部接口以使用嵌套格式。

如果這是不可能的,這裏有一些不太好的解決方法。

該查詢解析在同一水平的標準列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