我正在尝试将 SQL Server 结果转换为双重嵌套的 JSON 格式。
源 SQL Server 表:
ID | 姓名 | 程序 | 类型 | 部分 | 导向器 | 项目 | 高级经理 | PCM | 承包商 | 成本客户 |
---|---|---|---|---|---|---|---|---|---|---|
123 | 美国广播公司 | qw | 秋 | dd | 好久不见 | hkhjk | fghfgf | 关注 | 呸呸呸 | 呸呸呸 |
456 | 结衣 | gdfgf | 生长激素 | jkjlkll | uiop | 呸呸呸 | 射频识别 | ujmk | rfvtg | 蛋黄酱 |
转换为双重 JSON,如下所示:
[
[
{"key":"ID","value":"123"},
{"key":"Name","value":"abc"},
{"key":"Program","value":"qew"},
{"key":"Type","value":"tyu"},
{"key":"Section","value":"dd"},
{"key":"Director","value":"ghghjg"},
{"key":"Project","value":"hkhjk"},
{"key":"Sr Manager","value":"fghfgf"},
{"key":"PCM","value":"gnhghj"},
{"key":"Contractor","value":"gghgh"},
{"key":"Cost Client","value":"gghhg"}
],
[
{"key":"ID","value":"456"},
{"key":"Name","value":"yui"},
{"key":"Program","value":"gdffgf"},
{"key":"Type","value":"ghgfjhjhj"},
{"key":"Section","value":"jkjlkll"},
{"key":"Director","value":"uiop"},
{"key":"Project","value":"rtyuui"},
{"key":"Sr Manager","value":"rfv"},
{"key":"PCM","value":"ujmk"},
{"key":"Contractor","value":"rfvtg"},
{"key":"Cost Client","value":"efgg"}
]
]
任何帮助将不胜感激。
编辑:我从重写“FOR JSON AUTO”开始,这样我就可以以某种方式添加“Key”“Value”文本。但是因为我的表在列名中有空格,所以 FOR XML PATH('') 按照 FOR XML 错误的要求给出了无效的 XML 标识符。那是我想到接受社区帮助的时候。
Create PROCEDURE [dbo].[GetSQLtoJSON] @TableName VARCHAR(255)
AS
BEGIN
IF OBJECT_ID(@TableName) IS NULL
BEGIN
SELECT Json = '';
RETURN
END;
DECLARE @SQL NVARCHAR(MAX) = N'SELECT * INTO ##T ' +
'FROM ' + @TableName;
EXECUTE SP_EXECUTESQL @SQL;
DECLARE @X NVARCHAR(MAX) = '[' + (SELECT * FROM ##T FOR XML PATH('')) + ']';
SELECT @X = REPLACE(@X, '<' + Name + '>',
CASE WHEN ROW_NUMBER() OVER(ORDER BY Column_ID) = 1 THEN '{'
ELSE '' END + Name + ':'),
@X = REPLACE(@X, '</' + Name + '>', ','),
@X = REPLACE(@X, ',{', '}, {'),
@X = REPLACE(@X, ',]', '}]')
FROM sys.columns
WHERE [Object_ID] = OBJECT_ID(@TableName)
ORDER BY Column_ID;
DROP TABLE ##T;
SELECT Json = @X;
END
样本数据:
CREATE TABLE [dbo].[Test1](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Col1] [int] NOT NULL,
[Col 2] varchar(50)
) ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[Test1] ON
GO
INSERT [dbo].[Test1] ([ID], [Col1], [Col 2]) VALUES (1, 0,'ABCD')
GO
INSERT [dbo].[Test1] ([ID], [Col1] ,[Col 2]) VALUES (2, 1, 'POIU')
GO
SET IDENTITY_INSERT [dbo].[Test1] OFF
GO