假设我有一个表FamousPeople
和一个列Name
,并带有3个名称:
John
Mary
Freddie Mercury
这样做:
SELECT
'Some Random Value' AS someColumnName,
(SELECT name FROM FamousPeople
FOR JSON PATH) AS famousPeopleName
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
我得到这个结果:
{
"someColumnName": "Some Random Value",
"famousPeopleName":
[
{"name":"John"},
{"name":"Mary"},
{"name":"Freddie Mercury"}
]
}
我想知道是否有任何方法可以将famousPeopleName
结果列作为字符串数组获取:
{
"someColumnName": "Some Random Value",
"famousPeopleName":
[
"John",
"Mary",
"Freddie Mercury"
]
}
当然,仅使用T-SQL功能,就不会在T-SQL中使用疯狂的科学家字符串操作(在荷兰也称为kick)
答案 0 :(得分:0)
您可以使用JSON_QUERY
和FOR XML
构建数组,然后提取整个json片段:
declare @FamousPeople table([name] varchar(50))
insert into @FamousPeople values
('John'),('Mary'),('Freddie Mercury')
SELECT 'Some Random Value' AS someColumnName,
JSON_QUERY(
'[' + STUFF(( SELECT ',' + '"' + [name] + '"'
FROM @FamousPeople
FOR XML PATH('')),1,1,'') + ']' ) famousPeopleName
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
结果:
{
"someColumnName": "Some Random Value",
"famousPeopleName":
[
"John",
"Mary",
"Freddie Mercury"
]
}