我有几个未连接的表,但希望使用 SQL Server 使用 FOR JSON 将数据作为 JSON 从查询中返回,可能使用子查询?
创建表格;
DECLARE @Filter AS TABLE
(
filter_id int primary key,
filter_field varchar(255),
filter_values varchar(255)
)
DECLARE @Other AS TABLE
(
other_id int primary key,
other_field varchar(255),
other_values varchar(255)
)
DECLARE @Data AS TABLE
(
data_id int primary key,
Col1 varchar(255),
Col2 varchar(255),
Col3 varchar(255)
)
插入数据;
INSERT INTO @Filter (filter_id, filter_field,filter_values) VALUES
(1, 'SC.Type','Parent'),
(2, 'ScanDateTime','20200620')
INSERT INTO @Other (other_id, other_field,other_values) VALUES
(1, 'header','This is the header'),
(2, 'footer','This is the footer')
INSERT INTO @Data (data_id,Col1,Col2,Col3) VALUES
(1, 'Val1','Val2','Val3'),
(2, 'Val4','Val5','Val6'),
(3, 'Val7','Val8','Val9')
我一直在@Data 的每一行中重复使用@Filter 和@Other。
获取以下结果的 JSON 查询将是什么;
{
"filter":
[
{
"field":"SC.Type",
"values":"Parent"
},
{
"field":"ScanDateTime"
"values":"20200620"
}
],
"header":"This is the header",
"footer":"This is the footer",
"data":
[
{
"col1":"Val1",
"col2":"Val2",
"col3":"Val3"
},
{
"col1":"Val4",
"col2":"Val5",
"col3":"Val6"
},
{
"col1":"Val7",
"col2":"Val8",
"col3":"Val9"
}
]
}
任何帮助,将不胜感激。