如何在 MS SQL 2019 的 Json_Value 中使用带通配符的 JsonPath 表达式?

How to use JsonPath expression with wildcards in MS SQL 2019's Json_Value?

在我的 SQL Table 中,我有一个存储 JSON 的列,其结构类似于以下内容:

{
    "type": "Common",
    "items": [
        {
            "name": "landline",
            "number": "0123-4567-8888"
        },
        {
            "name": "home",
            "number": "0123-4567-8910"
        },
        {
            "name": "mobile",
            "number": "0123-4567-9910"
        }
    ]
}

这是我正在使用的 table 结构:

CREATE TABLE StoreDp(
[JsonData] [nvarchar](max), 
[Type] AS (json_value([JsonData],'lax $.type')) PERSISTED, 
[Items]  AS (json_value([JsonData],N'lax $.items[*].name')) PERSISTED
)

现在,当我尝试在 table 列 [JsonData] 中插入示例 JSON(序列化)时,出现错误

JSON path is not properly formatted. Unexpected character '*' is found at position 3.

我希望插入的数据在 [Items] 中的值为“[座机、家庭、移动]”

我已经验证了 jsonpath 表达式,它工作正常,除了在 SQL 服务器中。

更新:更正了 SQL 服务器版本。

SQL 服务器无法使用通配符路径和 JSON_VALUE.

进行粉碎和重建 JSON

您必须结合使用 OPENJSONSTRING_AGG,如果您希望结果有效,还必须使用 STRING_ESCAPE JSON。

SELECT
  (
    SELECT '[' + STRING_AGG('"' + STRING_ESCAPE(j.name, 'json') + '"', ',') + ']'
    FROM OPENJSON(sd.JsonData, '$.items')
      WITH (
        name varchar(20)
      ) j
  )
FROM StoreDp sd;

db<>fiddle

您只能使用标量 UDF 在计算列中执行此操作。然而,那些对性能有重大影响,通常应该避免。我建议你只做一个视图。