0

我正在尝试从语句中的 [key] 行值中创建一个 select * from openjson(@json)表。openjson(@json) 语句为我提供了包含 53 个 [key] 行值的结果,这是一个小片段:

[key]      [value]                    [type]
_id        5b05390c5d222f0059209918   1
ean        65485555                   1
name       NULL                       0
holder     {"_id":"5b0538355d222f00585db6f1","name":"***... 5
root       {"_id":"5b05390c5d222f005920990a","holder":{"_id":"5b0538885... 5 
assigner   {"_id":"5b0538885d222f00570aca19","name":"***... 5
created    2018-05-23T09:49:00+0000   1
children   []                         4
address                               1
timezone   Etc/GMT-1                  1

我想要一个看起来像这样的表:

    table1
[_id]                    [ean]    [name] [holder]                  [etc...]
5b05390c5d222f0059209918 65485555 NULL   {"_id":"5b0538355d222...}

我还希望能够将另一个 JSON 中的值插入到同一个表中

insert into table1 () 
select [value] from openjson(@json2)

谢谢!

4

1 回答 1

0

只需在您的 OPENJSON 查询中添加 WITH 子句。

请参阅OPENJSON,例如:

DECLARE @json NVARCHAR(MAX) = N'[  
  {  
    "Order": {  
      "Number":"SO43659",  
      "Date":"2011-05-31T00:00:00"  
    },  
    "AccountNumber":"AW29825",  
    "Item": {  
      "Price":2024.9940,  
      "Quantity":1  
    }  
  },  
  {  
    "Order": {  
      "Number":"SO43661",  
      "Date":"2011-06-01T00:00:00"  
    },  
    "AccountNumber":"AW73565",  
    "Item": {  
      "Price":2024.9940,  
      "Quantity":3  
    }  
  }
]'  

SELECT *
FROM OPENJSON ( @json )  
WITH (   
              Number   varchar(200)   '$.Order.Number',  
              Date     datetime       '$.Order.Date',  
              Customer varchar(200)   '$.AccountNumber',  
              Quantity int            '$.Item.Quantity',  
              [Order]  nvarchar(MAX)  AS JSON  
 )
于 2018-06-07T17:26:16.007 回答