如何将所有连接表中的所有结果组合为一个JSON输出

发布于 2025-02-08 22:05:08 字数 794 浏览 2 评论 0原文

我正在加入一些表,使用JSON路径进行输出,但我只想以某种结构化的方式观察所有表的数据。

SELECT 
tableOne.attrA AS 'tableOne.attrA',
tableOne.attrB AS 'tableOne.attrB',
...
tableTwo.attrB AS 'tableTwo.attrB'
...
FROM tableOne
JOIN tableTwo 
  ON tableOne.fId = tableTwo.id
FOR JSON PATH

并获得输出之类的:

{
   "tableOne": {
         "attrA": "asdf"
    }
   "tableOne": {
         "attrB": "fdsa"
    }
}

我想对所有值都有符号,例如:

SELECT 
tableOne.* AS 'tableOne.*',
tableTwo.* AS 'tableTwo.*',
tableThree.* AS 'tableThree.*
....
FOR JSON PATH;

我看到json_array,可以与json_object 结合使用,但它仅在SQL Server 2022中。我有2019版。

I'm joining some tables, using FOR JSON PATH for output, but I just want to observe data from all the tables in some structured manner.

SELECT 
tableOne.attrA AS 'tableOne.attrA',
tableOne.attrB AS 'tableOne.attrB',
...
tableTwo.attrB AS 'tableTwo.attrB'
...
FROM tableOne
JOIN tableTwo 
  ON tableOne.fId = tableTwo.id
FOR JSON PATH

And get output like:

{
   "tableOne": {
         "attrA": "asdf"
    }
   "tableOne": {
         "attrB": "fdsa"
    }
}

I would like to have somethign for all the values like:

SELECT 
tableOne.* AS 'tableOne.*',
tableTwo.* AS 'tableTwo.*',
tableThree.* AS 'tableThree.*
....
FOR JSON PATH;

I saw JSON_ARRAY which can be combined with JSON_OBJECT but it's only in SQL Server 2022. I have 2019 version.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

指尖凝香 2025-02-15 22:05:08

因此,我找到了解决方案:

SELECT 
json_query((
        select t1.* 
        for json path,
        without_array_wrapper -- if its only one match
        ,INCLUDE_NULL_VALUES -- if we want to see null values
        )) as tableOne,
json_query((
        select t2.* 
        for json path,
        without_array_wrapper -- if its only one match
        )) as tableTwo
...
FROM tableOne t1
JOIN tableTwo t2
  ON t1.fId = t2.id
FOR JSON PATH, -- needs to be PATH; AUTO returns hierarchy which is just cascading encapsulation
INCLUDE_NULL_VALUES -- just for the sake of seeing all null values

这将在形成的JSON中输出所有数据。我会添加一些链接到MS Docu,但稍后。

So I found the solution:

SELECT 
json_query((
        select t1.* 
        for json path,
        without_array_wrapper -- if its only one match
        ,INCLUDE_NULL_VALUES -- if we want to see null values
        )) as tableOne,
json_query((
        select t2.* 
        for json path,
        without_array_wrapper -- if its only one match
        )) as tableTwo
...
FROM tableOne t1
JOIN tableTwo t2
  ON t1.fId = t2.id
FOR JSON PATH, -- needs to be PATH; AUTO returns hierarchy which is just cascading encapsulation
INCLUDE_NULL_VALUES -- just for the sake of seeing all null values

And this outputs all the data in formated JSON. I would add some links to ms docu, but later.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文