【发布时间】:2020-04-06 05:59:48
【问题描述】:
我正在尝试将一行数据转换为包含单个对象的 JSON 数组。一列包含 XML,它概述了另一个转换为数组的单个对象。
我的查询:
WITH r AS (
SELECT TOP 1 * FROM Table1
ORDER BY RecordID ASC)
SELECT
NEWID() AS 'Report.ReportUUID',
Value1 as 'Report.Value1',
Value2 as 'Report.Value2',
DateTime as 'Report.DateTime',
UserID as 'Report.UserID',
'Medium' as 'Report.Priority',
NEWID() as 'Report.Item.ItemUUID',
XML.value('category[1]', 'varchar(100)') as 'Report.Item.Category',
XML.value('description[1]', 'varchar(1000)') as 'Report.Item.Description',
XML.value('date[1]', 'varchar(100)') AS 'Report.Item.DateTime'
FROM r
FOR JSON PATH, ROOT('DataSet');
期望的输出:
{
"DataSet" : {
"Report" : [
{
"ReportUUID" : "uuid here",
"Value1" : "value1",
"Value2" : "value2",
"DateTime" : "2020-04-06 16:00:00",
"UserID" : "1234",
"Priority" : "Medium",
"Item" : [
{
"ItemUUID" : "uuid here",
"Category" : "01",
"Description" : "Desc",
"DateTime" : "2020-04-05 08:00:00"
}
]
}
]
}
}
实际输出:
{
"DataSet": [
{
"Report": {
"ReportUUID" : "uuid here",
"Value1": "value1",
"Value2": "value2",
"DateTime": "2020-04-06 16:00:00",
"UserID": "1234",
"Priority": "Medium",
"Item": {
"ItemUUID": "uuid here",
"Category": "01",
"Description": "Desc",
"DateTime": "2020-04-05 08:00:00"
}
}
}
]
}
DataSet 必须是单个对象,Report 和 Item 必须是包含单个对象的数组。任何人都可以帮助格式化这样的数据吗?
【问题讨论】:
-
使用的 SQL Server 版本是什么?
-
Microsoft SQL Server 2017,版本 13.0.5101.9
标签: sql json sql-server tsql