2017-09-07 1 views
1

Je me bats comment formater ma procédure stockée pour créer une chaîne de données JSONprocédure stockée sélectionner des données JSON

J'ai cet exemple de requête où, en i besoin de formater la chaîne JSON comme celui-ci

{"Résumé": "Nom d'utilisateur du changement d'employé", "DateModified": "2017/09/06", "Modifications": [{"Propriété": "test", "ancien": "10", "nouveau": "1"}, {"Property": "test", "old": "10", "new": "2"}, {"Propriété": "test", "old": "10", "new" ":" 3 "}, {" Propriété ":" test "," ancien ":" 10 "," nouveau ":" 4 "}, {" Propriété ":" test "," ancien ":" 10 ", "nouveau": "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') 

Actuellement ma sortie est toujours comme ce

{ "CommitteeMembers": [{ "Propriété": "test", "vieux": "10", "nouveau": "1"}, {"Propriété": "test", "ancien": "10", "nouveau": "2"}, {"Propriété": "test", "ancien": "10", "nouveau": "3" }, {"Propriété": "test", "ancien": "10", "nouveau": "4"}, {"Propriété": "test", "ancien": "10", "nouveau": " 5" }]}

Heres le dbfiddle link

Répondre

0

Vous devrez peut-être utiliser un curseur ici

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":"'[email protected]+'","old":"'[email protected]+'","new":"'[email protected]+'"}' 
FETCH NEXT FROM @new_Cursor INTO @Property,@oldValue,@newValue 
    end 
    CLOSE @new_Cursor 
    DEALLOCATE @new_Cursor 
    set @jsonResult = @jsonResult + ']}' 

    select @jsonResult as Result 

Mise à jour

La question est avec votre sélection Déclaration

Working img enter image description here

+0

CURSEUR n'est pas autorisée dans l'instruction FOR JSON - des thats l'erreur –

+0

peut vous montrer votre table JSON defination –

+0

voir le lien dbdiffle ici http://dbfiddle.uk/?rdbms=sqlserver_2016&fiddle=db2669c3863b41db46391a0f55e8bc60 –