在SQL Server中使用JSON格式的值查询JSON键

t3psigkw  于 2023-06-25  发布在  SQL Server
关注(0)|答案(1)|浏览(173)

我有这些JSON

Application 1:

{
"business_industry": "Agriculture",
"docs": [
    {
    "internal": false,
    "type": "Asset & Liability Statement"
    },
    {
    "internal": false,
    "name": "Privacy Consent",
    "type": "Privacy Consent"
    }
],
"quote": {
    "principal": 0,
    "short_id": "3856545"
}
}

Application 2:

{
"business_industry": "Construction",
"docs": [
    {
    "internal": false,
    "name": "Privacy Consent",
    "type": "Privacy Consent"
    }
],
"asset": {
    "model": null,
    "make": "3856545"
}
}

Application 3:

{
"business_industry": "Coal Mining",
"business_business_names": [
    {
    "business_organisation_name": "Centron Consulting Services",
    "business_effective_from": "2018-04-11"
    }
],
"lite_doc": {
    "total_sales": 0,
    "total_sales2": 0,
    "refunds_present": false,
    "payment_arrangement_evident": false
}
}

这是从我的Application模型中的DataReceived推导出来的。
我想查询所有的应用程序,并获得与对象作为值的键。
类似于:

+----------+-----------+-------+----------------------------+-----------------------------+
|   docs   | quotes    | asset | business_business_names    | lite_doc                    |
+----------+-----------+-------+----------------------------+-----------------------------+
| internal | principal | model | business_organisation_name | total_sales                 |
| type     | short_id  | make  | business_effective_from    | total_sales2                |
| name     |           |       |                            | refunds_present             |
|          |           |       |                            | payment_arrangement_evident |
+----------+-----------+-------+----------------------------+-----------------------------+

这段代码就是我目前所拥有的:

BEGIN TRANSACTION;

BEGIN TRY
SELECT
    asset.[key] AS asset
FROM dbo.Application
-- SELECT ALL KEYS THAT HAVE OBJECTS AS VALUES AND DISPLAY THOSE OBJECTS' KEYS
CROSS APPLY OPENJSON(DataReceived, '$.asset') AS asset;
END TRY
BEGIN CATCH
-- Do nothing 
END CATCH

ROLLBACK TRANSACTION;

但它只能查询asset,而不是DISTINCT

由于某些原因,DISTINCT在查询中不起作用。

我如何达到预期的结果?

k5ifujac

k5ifujac1#

请尝试使用此代码

BEGIN TRY

SELECT DISTINCT
    key, value.*
FROM dbo.Application
CROSS APPLY OPENJSON(DataReceived) AS value WHERE value IS NOT NULL AND JSON_TYPE(value) = 'object';

END TRY
BEGIN CATCH
-- Do nothing 
END CATCH

ROLLBACK TRANSACTION;

1.添加select distinct将从dbo.Application中选择不同的键。2)OPENJSON函数用于解析(DataReceived)列,每个键具有不同的值。

相关问题