You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过SQL OPENJSON仅提取JSON字符串中的第一个元素数据

解决方案

直接定位JSON数组的第一个元素,或者用TOP 1限制结果即可,同时需要修正你原查询中的路径错误:

方法一:直接读取数组第一个元素

通过在OPENJSON的路径末尾添加[0],直接定位到wd:Transaction_Log_Entry数组的第一个元素,确保只返回一行数据:

SELECT Effective_Moment, Entry_Moment  
FROM [dbo].[Daily_And_Future_Terminations_Transaction_Log_Source] 
CROSS APPLY OPENJSON (Transaction_Log_Entry_Data, '$[0]."wd:Transaction_Log_Entry"[0]')
WITH (
        Effective_Moment NVARCHAR(50) '$."wd:Transaction_Log_Data"."wd:Transaction_Effective_Moment"',
        Entry_Moment NVARCHAR(50) '$."wd:Transaction_Log_Data"."wd:Transaction_Entry_Moment"'
       )

方法二:用TOP 1限制结果

保留原有的数组展开逻辑,通过TOP 1配合排序(按记录时间降序)确保拿到最新的记录,即使数组顺序发生变动也能保证正确性:

SELECT TOP 1 Effective_Moment, Entry_Moment  
FROM [dbo].[Daily_And_Future_Terminations_Transaction_Log_Source] 
CROSS APPLY OPENJSON (Transaction_Log_Entry_Data, '$[0]."wd:Transaction_Log_Entry"')
WITH (
        Effective_Moment NVARCHAR(50) '$."wd:Transaction_Log_Data"."wd:Transaction_Effective_Moment"',
        Entry_Moment NVARCHAR(50) '$."wd:Transaction_Log_Data"."wd:Transaction_Entry_Moment"'
       )
ORDER BY Entry_Moment DESC

关键修正点

你原查询中的路径存在错误:$."."wd:Transaction_Log_Data"多了一个多余的点,必须改成$."wd:Transaction_Log_Data"才能正确解析JSON字段。

内容的提问来源于stack exchange,提问作者OJ Slott

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 16:55:22