我正在将一个非常简单的JSON文件引入MS SQL DB。我已经创建了表,当我进行查询时,我可以很好地处理所有数据,除了嵌套的名为“地址”的部分
JSON的代码段
{
"sold_price": Sample,
"auction_date": "Sample",
"address": {
"state": "Sample",
"street": "Sample",
"number": "Sample",
"suburb": "Sample",
"postcode": "Sample",
"country": "Sample"
},
},
"REA_Agent": "Sample",
"sale_date": "2018-08-03 00:13:04+00:00",
},
加载JSON的过程:
DECLARE @BT1 VARCHAR(MAX)
SELECT @BT1 =
BulkColumn
FROM OPENROWSET(BULK'C:\JSON Test\BT1.json', SINGLE_BLOB) JSON
SELECT @BT1 as BT1_Table;
IF (ISJSON(@BT1) = 1)
BEGIN
PRINT 'JSON File is valid';
INSERT INTO BT1
SELECT *
FROM OPENJSON(@BT1)
WITH(
[state] VARCHAR(MAX) '$.state',
[number] VARCHAR(MAX) '$.number',
[street] VARCHAR(MAX) '$.street',
[suburb] VARCHAR(MAX) '$.suburb',
[postcode] INTEGER '$.postcode',
[property_type] VARCHAR(MAX) '$.property_type',
[sold_price] VARCHAR(MAX) '$.sold_price',
[sold_date] DATE '$.sold_date',
[settlement_date] DATE '$.settlement_date',
[agency_name] VARCHAR(MAX) '$.agency_name',
[bedrooms] INTEGER '$.bedrooms',
[bathrooms] INTEGER '$.bathrooms',
[parking] INTEGER '$.parking',
[auction_date] DATE '$.auction_date',
[passed_in] VARCHAR(MAX) '$.passed_in',
[will_disclose_sold] VARCHAR(MAX) '$.will_disclose_sold'
)
END
ELSE
BEGIN
PRINT 'JSON File is invalid';
END
什么不起作用:
加载后-我只运行了一个基本的Select *来查看,“地址”中的所有字段都返回NULL。
我在这里缺少一个窍门吗?我所有的电话都返回NULL,但我不是100%知道为什么。(很高兴收到我的代码的反馈,如果我可以缩短流程/错误的话)
答案 0 :(得分:1)
您要从称为address
的嵌套元素中读取数据,因此必须在.address
子句中为来自嵌套部分的每个值指定WITH
:
INSERT INTO BT1
SELECT *
FROM OPENJSON(@BT1)
WITH(
[state] VARCHAR(MAX) '$.address.state', --<< added ".address"
[number] VARCHAR(MAX) '$.address.number', --<< added ".address"
[street] VARCHAR(MAX) '$.address.street', --<< added ".address"
[suburb] VARCHAR(MAX) '$.address.suburb', --<< added ".address"
[postcode] INTEGER '$.address.postcode',--<< added ".address"
[sold_price] VARCHAR(MAX) '$.sold_price',
[auction_date] DATE '$.auction_date',
[sold_date] DATE '$.sold_date',
[settlement_date] DATE '$.settlement_date',
[agency_name] VARCHAR(MAX) '$.agency_name',
[bedrooms] INTEGER '$.bedrooms',
[bathrooms] INTEGER '$.bathrooms',
[parking] INTEGER '$.parking',
[passed_in] VARCHAR(MAX) '$.passed_in',
[will_disclose_sold] VARCHAR(MAX) '$.will_disclose_sold',
[property_type] VARCHAR(MAX) '$.property_type'
)
结果:
注意:由于您的json片段显然无效(括号不匹配,sold_price
的值未加引号,postcode
应该是整数,但值是"sample"
等。),我使用以下json测试上述代码:
{
"sold_price": "100",
"auction_date": "2018-01-01",
"address": {
"state": "NY",
"street": "street name",
"number": "123",
"suburb": "suburb name",
"postcode": 12345,
"country": "US"
},
"REA_Agent": "REA_Agent name",
"sale_date": "2018-08-03 00:13:04+00:00"
}
如果这与您的结构不同,请更新您的问题,并告诉我。