簡體   English   中英

用於JSON數據的存儲過程選擇

[英]Stored procedure select for json data

我一直在努力如何格式化存儲過程以創建json字符串數據

我有這個示例查詢,在這里我需要像這樣格式化json字符串

{“摘要”:“員工更改用戶名”,“ DateModified”:“ 2017/09/06”,“更改”:[{“屬性”:“測試”,“舊”:“ 10”,“新”:” 1“},{” Property“:” test“,” old“:” 10“,” new“:” 2“},{” Property“:” test“,” old“:” 10“,” new“ :“ 3”},{“ Property”:“ test”,“ old”:“ 10”,“ new”:“ 4”},{“ Property”:“ test”,“ old”:“ 10”,“ new“:” 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”:[{“ Property”:“ test”,“ old”:“ 10”,“ new”:“ 1”},{“ Property”:“ test”,“ old”:“ 10”,“ new“:” 2“},{” Property“:” test“,” old“:” 10“,” new“:” 3“},{” Property“:” test“,” old“:” 10“ ,“新”:“ 4”},{“屬性”:“測試”,“舊”:“ 10”,“新”:“ 5”}]}

這是dbfiddle 鏈接

您可能需要在此處使用光標

 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

更新資料

問題在於您的選擇聲明

工作img 在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM