Could not create the JSON-formatted Column in SQL Table with including NULL Values

130 views Asked by At

I need to combine in one Table the SQL Data with columns, formatted as JSON. The Json columns are a vary length, from 4 to 5 Columns. So I need to add one optional NULL column to the JSON String, when the Length is 4. But if I put the 4-Places Json String in my Function, I get no results

What is wrong In folowing Function?

DECLARE @json1 nvarchar(max),
        @json2 nvarchar(max)

--SET @json1 = '{"Inst":[{"id":-627706141,"Instances":"Inst22"}
--,{"id":-627706141,"Instances":"20200605"}
--,{"id":-627706141,"Instances":"Sometghing"}
--,{"id":-627706141,"Instances":"SomeServer"}
--,{"id":-627706141,"Instances":"OptionalServer"}]}'
SET @json1 = '{"Inst":[{"id":1505267576,"Instances":"Inst22"}
,{"id":1505267576,"Instances":"20190630"}
,{"id":1505267576,"Instances":"Something"}
,{"id":1505267576,"Instances":"SomeServer"}]}'
SET @json2 = '{"Value":[{"id":-627706141,"Werte":"Intel(R) Xeon(R) CPU E5-2690 v3 "},{"id":-627706141,"Werte":" 2.60GHz"}]}'

SELECT * 
FROM 
 (
    SELECT *
    FROM OPENJSON( @json1 )
    WITH
    ( IID sys.int '$.Inst[0].id',
        sidInstance           sys.NVARCHAR( 50 ) '$.Inst[1].Instances',
        DatumInstance         sys.NVARCHAR( 50 ) '$.Inst[2].Instances',
        ServerInstance        sys.NVARCHAR( 50 ) '$.Inst[3].Instances',
        VirtualServerInstance sys.NVARCHAR( 50 ) '$.Inst[4].Instances',
        OptionalInstance      sys.NVARCHAR( 50 ) '$.Inst[5].Instances'
    ) a
inner join 
   OPENJSON( @json2 )
    WITH
    ( WID sys.int '$.Value[0].id',
        CPUType               sys.NVARCHAR( 50 ) '$.Value[0].Werte',
        Frequency             sys.NVARCHAR( 50 ) '$.Value[1].Werte'
    ) b on a.IID = b.WID
) t FOR JSON PATH , INCLUDE_NULL_VALUES ``` 
1

There are 1 answers

1
SteveC On BEST ANSWER

The id field values do not equal. If the id field is set to -627706141 in @json1, so that it matches @json2, then the output is as follows

[
  {
    "IID": -627706141,
    "sidInstance": "20190630",
    "DatumInstance": "Something",
    "ServerInstance": "SomeServer",
    "VirtualServerInstance": null,
    "OptionalInstance": null,
    "WID": -627706141,
    "CPUType": "Intel(R) Xeon(R) CPU E5-2690 v3 ",
    "Frequency": " 2.60GHz"
  }
]