从具有 2 列(键和值)的 table,如何 return 具有列值的 json?

From a table with 2 columns (key and value), how to return a json with values of the column?

我有一个包含 2 列的 table:

declare @myTable table ([Key] nvarchar(max), [value] nvarchar(max)) 
insert into @myTable ([key],value) values ('Timestamp', convert(varchar(max), getdate(), 120))
insert into @myTable ([key],value) values ('Number', '123456')

我想从这个 table 中得到一个 JSON,格式如下:

[{"Timestamp":"2021-08-27 11:19:38"},{"Number":"123456"}]

我这样查询:

SELECT [key],[value] FROM @myTable FOR JSON AUTO

但结果是:

{"key":"Timestamp","value":"2021-08-27 11:19:38"},{"key":"Number","value":"123456"}

有办法吗?

你需要先旋转它

SELECT
  [Timestamp],
  [Number]
-- if you want it as a number, not text, then use:
-- CAST([Number] AS int) [Number]
FROM @myTable t
PIVOT (
    MAX(value) FOR [key] IN ([Timestamp], [Number])
) pvt
FOR JSON PATH

db<>fiddle