1

我需要将 SQL 数据与列合并到一个表中,格式为 JSON。Json 列的长度不同,从 4 列到 5 列。因此,当长度为 4 时,我需要在 JSON 字符串中添加一个可选的 NULL 列。但是如果我将 4-Places Json 字符串放入我的函数中,则不会得到任何结果

以下功能有什么问题?

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 ``` 
4

1 回答 1

0

id 字段值不相等。如果@json1中的id字段设置为-627706141,使其匹配@json2,那么输出如下

[
  {
    "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"
  }
]
于 2020-10-19T21:17:08.380 回答