存储过程选择json数据

时间:2017-09-07 05:38:58

标签: sql sql-server stored-procedures

我一直在努力如何格式化我的存储过程以创建json字符串数据

我有这个示例查询,我需要像这样格式化json字符串

  

{"摘要":"员工更改用户名"," DateModified":" 2017/09/06","变化":[{"属性":"测试""旧":" 10""新&#34 ;:" 1"},{"属性":"测试""旧":" 10",& #34;新":" 2"},{"属性":"测试""旧":" 10""新":" 3"},{"属性":"测试""旧&#34 ;:" 10""新":" 4"},{"属性":"测试",& #34;旧":" 10""新":" 5"}]}

DECLARE @membersJSON NVARCHAR(MAX) = '[1,2,3,4,5]';
DECLARE @commiteeID INT = 10;
DECLARE @jsonData NVARCHAR(MAX);

DECLARE @jsonTable TABLE(
    Property nvarchar(max),
    old nvarchar(max),
    new nvarchar(max));

INSERT INTO @jsonTable SELECT 'test' as Property,@commiteeID AS old,m.value AS new
FROM OPENJSON(@membersJSON) as m;

SELECT * FROM @jsonTable FOR JSON PATH, ROOT ('CommitteeMembers')

目前我的输出仍然是这样的

  

{" CommitteeMembers":[{"属性":"测试""旧":" 10" "新":" 1"},{"属性":"测试""旧":&# 34; 10""新":" 2"},{"属性":"测试""旧& #34;:" 10""新":" 3"},{"属性":"测试" "旧":" 10""新":" 4"},{"属性":&# 34;测试""旧":" 10""新":" 5"}]}

继承dbfiddle link

1 个答案:

答案 0 :(得分:0)

您可能需要在此处使用光标

 declare @new_Cursor as CURSOR 
 declare @Property varchar(10)   
 declare @oldValue varchar(10)   
 declare @newValue varchar(10)   
 declare @jsonResult nvarchar(max) ='{"CommitteeMembers":['
set @new_Cursor = CURSOR FOR SELECT * FROM @jsonTable FOR JSON PATH, ROOT 
('CommitteeMembers')
    OPEN @new_Cursor
    FETCH NEXT FROM @new_Cursor INTO @Property,@oldValue,@newValue
    WHILE @@FETCH_STATUS = 0
    Begin
      if(@jsonResult<>'{"CommitteeMembers":[') --To separate the objects
          begin
               set @jsonResult = @jsonResult + ','
          end 
      set @jsonResult = @jsonResult + 
'{"Property":"'+@Property+'","old":"'+@oldValue+'","new":"'+@newValue+'"}'
 FETCH NEXT FROM @new_Cursor INTO @Property,@oldValue,@newValue
    end
    CLOSE @new_Cursor
   DEALLOCATE @new_Cursor
   set @jsonResult = @jsonResult + ']}'

  select @jsonResult as Result

更新

问题在于您的选择声明

Working img enter image description here