Другой возможный подход с использованием комбинации FOR JSON
и манипуляции со строками, но без динамического оператора:
Введите:
CREATE TABLE #tblKeywords (
Id int,
[Keyword] nvarchar(50),
[Text] nvarchar(50),
[Value] nvarchar(50)
);
INSERT INTO #tblKeywords
(ID, [Keyword], [Text], [Value])
VALUES
(4, 'Category', 'A', '10'),
(5, 'Category', 'B', '20'),
(1, 'Season', 'Winter', '1'),
(2, 'Season', 'Spring', '2'),
(3, 'Season', 'Summer', '3'),
(9, 'Season', 'Fall', '4'),
(6, 'UnitType', 'Ft', 'Feet'),
(7, 'UnitType', 'Set', 'Set'),
(8, 'UnitType', '$', 'Dollar')
T-SQL:
SELECT CONCAT(
N'{"Keywords":[',
STUFF(
(
SELECT DISTINCT CONCAT(N',{"', k.[Keyword], '":', c.[Json], N'}')
FROM #tblKeywords k
CROSS APPLY (
SELECT [Value], [Text]
FROM #tblKeywords
WHERE [Keyword] = k.[Keyword]
FOR JSON PATH
) c([Json])
FOR XML PATH('')
), 1, 1, N''
),
N']}'
) AS JsonOutput
Выход:
JsonOutput
{"Keywords":[{"Category":[{"Value":"10","Text":"A"},{"Value":"20","Text":"B"}]},{"Season":[{"Value":"1","Text":"Winter"},{"Value":"2","Text":"Spring"},{"Value":"3","Text":"Summer"},{"Value":"4","Text":"Fall"}]},{"UnitType":[{"Value":"Feet","Text":"Ft"},{"Value":"Set","Text":"Set"},{"Value":"Dollar","Text":"$"}]}]}