开发者

Create json object in SQL stored procedure based on input parameters

I need to create a json object in a stored procedure based on input parameters. The following works, but it's not very elegant and I am looking for a more 开发者_StackOverflowelegant solution.

-- adding log entry
declare @logjson nvarchar(max); 

set @logjson = concat(       '{"InputParameters":[', '{');
set @logjson = concat(@logjson, '"MacOwner":"', @Owner, '",');
set @logjson = concat(@logjson, '"EMS":"', @EMS, '",');
set @logjson = concat(@logjson, '"AXBomId":"', @AXBomId, '",');
set @logjson = concat(@logjson, '"Serial":"', @SerialId, '",');
set @logjson = concat(@logjson, '"Device":"', @AXItem, '",');
set @logjson = concat(@logjson, '"HWDevice":"', @HWDevice, '",');
set @logjson = concat(@logjson, '"TestPCHostName":"', @TestPCHostName, '",');
set @logjson = concat(@logjson, '"TestSWVersion":"', @TestSWVersion, '"');  --Last parameter no comma
set @logjson = concat(@logjson, '}],');
set @logjson = concat(@logjson, '"OutputParameters":[','{');
set @logjson = concat(@logjson, '"MACAddress":"', @MACAddress, '"');
set @logjson = concat(@logjson, '}');
set @logjson = concat(@logjson, ']' );
set @logjson = concat(@logjson, '}');

I tried to use the SELECT xxxxx FOR JSON AUTO - but this requires at least one table in the select statement.


You can select from a subquery. For example

declare @Owner varchar(5) ='ow123', @AXBomId int =11

select * from (
   select @Owner as MacOwner,  @AXBomId as AXBomId
) t
for json auto

returns

[{"MacOwner":"ow123","AXBomId":11}]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜