从 table 列名称和数据创建 json 键值

Create json key value from table column name and data

是否可以从 table SELECT 语句创建 JSON 键值,其中列名作为键,列值作为值

declare @T table(Id int, ItemName varchar(10), CategoryId int, ItemDate date)
insert into @T
values(1,'ABC',100, '1/1/2020')

到return如下

{
    "id": 1,
    "table": "tableName",
    "data": [{
            "key": "ItemName",
            "value": "ABC"
        },
        {
            "key": "CategoryId",
            "value": "100"
        },
        {
            "key": "ItemDate",
            "value": "1/1/2020"
        }
    ]
}

我考虑过选择 JSON 但卡在这里

select *
from @T 
for json auto

您可以尝试使用 VALUES table 值构造函数和 FOR JSON AUTO。正如文档中的 mentioned 一样,当 ... 您指定 AUTO 选项时,JSON 输出的格式将根据 [=31] 中列的顺序自动确定=] 列表及其来源 tables.

Table:

CREATE TABLE Tbl (
   Id int, 
   ItemName varchar(10), 
   CategoryId int, 
   ItemDate date
)
INSERT INTO Tbl
VALUES 
   (1, 'ABC', 100, '1/1/2020'),
   (2, 'DEF', 200, '2/2/2020')

声明:

SELECT t.Id, data.[key], data.[value]
FROM Tbl t
CROSS APPLY (VALUES 
   ('ItemName', CONVERT(varchar(max), ItemName)),
   ('CategoryId', CONVERT(varchar(max), CategoryId)),
   ('ItemDate', CONVERT(varchar(max), ItemDate))
) Data ([key], [value])
FOR JSON AUTO

结果:

[
   {
      "Id":1,
      "Data":[
         {"key":"ItemName", "value":"ABC"},
         {"key":"CategoryId","value":"100"},
         {"key":"ItemDate","value":"2020-01-01"}
      ]
   },
   {
      "Id":2,
      "Data":[
         {"key":"ItemName", "value":"DEF"},
         {"key":"CategoryId", "value":"200"},
         {"key":"ItemDate", "value":"2020-02-02"}
      ]
   }
]

作为附加选项,您可以尝试为每一行构建内部 JSON:

SELECT 
   Id, 
   (
   SELECT [key], [value]
   FROM (VALUES
      ('ItemName', CONVERT(varchar(max), ItemName)),
      ('CategoryId', CONVERT(varchar(max), CategoryId)),
      ('ItemDate', CONVERT(varchar(max), ItemDate))
   ) v ([key], [value])
   FOR JSON PATH
   ) AS Data
FROM Tbl
FOR JSON AUTO