JSON stored in a column 'DataJson' in table
[{
"KickOffDate": "1-Jan-2019",
"TeamSize": "11",
"ClientEngineer": "Sagar",
"WaitingPeriod": "16.5"
}]
Query
SELECT JSON_VALUE(DataJson,'$.KickOffDate') AS KickOffDate
, JSON_VALUE(DataJson,'$.ClientEngineer') AS ClientEngineer
FROM [ABC].[Deliver]
Result
KickOffDate ClientEngineer
NULL NULL
Result should be:
KickOffDate ClientEngineer
1-Jan-2019 Sagar
答案 0 :(得分:0)
至少从SQL Server的JSON API的角度来看,您的JSON似乎格式错误。根据我的阅读,如果您的JSON数据由顶级JSON数组组成,则该数组需要有一个键名,并且所有内容都应包装在{ ... }
中。
以下设置已经过测试并且可以正常工作:
WITH yourTable AS (
SELECT '{ "data" : [{"KickOffDate": "1-Jan-2019", "TeamSize": "11", "ClientEngineer": "Sagar", "WaitingPeriod": "16.5"}] }' AS DataJson
)
SELECT
JSON_VALUE(DataJson, '$.data[0].KickOffDate') AS KickOffDate,
JSON_VALUE(DataJson, '$.data[0].ClientEngineer') AS ClientEngineer
FROM yourTable;
这是我使用的输入JSON的样子:
{
"data" : [
{
"KickOffDate": "1-Jan-2019",
"TeamSize": "11",
"ClientEngineer": "Sagar",
"WaitingPeriod": "16.5"
}
]
}
答案 1 :(得分:0)
您的sql查询错误。
您必须更正如下所示的查询。
SELECT JSON_VALUE(DataJson,'$[0].KickOffDate') AS KickOffDate ,JSON_VALUE(DataJson,'$[0].ClientEngineer') AS ClientEngineer FROM [ABC].[Deliver]
表中存储的数据不是JSON对象,而是JSON数组。
因此,为了获取JSON Object的每个值,需要在JSON Array中设置JSON Object的索引。
否则,您可以将数据存储为JSON对象,然后查询就可以正常工作。
答案 2 :(得分:0)
您有一个包含一个项目的JSON数组。假设您只对第一项感兴趣,则只需添加[0]
:
SELECT JSON_VALUE(DataJson,'$[0].KickOffDate') AS KickOffDate
, JSON_VALUE(DataJson,'$[0].ClientEngineer') AS ClientEngineer
FROM (
SELECT '[{
"KickOffDate": "1-Jan-2019",
"TeamSize": "11",
"ClientEngineer": "Sagar",
"WaitingPeriod": "16.5"
}]'
) AS t(DataJson)
如果要遍历所有项目,则需要使用OPENJSON
:
SELECT KickOffDate, ClientEngineer
FROM (
SELECT '[{
"KickOffDate": "1-Jan-2019",
"TeamSize": "11",
"ClientEngineer": "Sagar",
"WaitingPeriod": "16.5"
}, {
"KickOffDate": "1-Jan-2019",
"TeamSize": "11",
"ClientEngineer": "Sagar",
"WaitingPeriod": "16.5"
}, {
"KickOffDate": "1-Jan-2019",
"TeamSize": "11",
"ClientEngineer": "Sagar",
"WaitingPeriod": "16.5"
}]'
) AS t(DataJson)
CROSS APPLY OPENJSON(DataJson)
WITH (
KickOffDate VARCHAR(100) '$.KickOffDate',
ClientEngineer VARCHAR(100) '$.ClientEngineer'
)