首页 > 解决方案 > 在 Analysis Services 中使用 SQL Server 动态 JSON?

问题描述

我试图让我的头脑围绕哪个方向甚至从以下开始..

对我存储在 SQL Server 2016+ 中的动态表单 (JSON) 进行成像。到目前为止,我已经看到/尝试了几个动态查询来获取动态 JSON 并将其展平为列。

鉴于“动态”性质,很难“存储”使数据变平的数据。我一直在查看临时/临时/内存表,以在“相对较短的时间内”(比如一两个小时)存储动态扁平数据。

我还被问到是否可以使用动态 JSON 数据在 Analysis Services 中构建多维数据集。再次考虑到这种动态性质,这样的事情甚至可能吗?

我想我的问题有两个:

  1. 在 SQL Server 中展平动态 JSON 的指针
  2. 是否可以采用动态 JSON、展平为列并以某种方式在 Analysis Services 中使用?即最终在多维数据集中使用?

意识到上述内容有点含糊,但任何能让我朝着正确方向前进的指针都将不胜感激!

非常感谢。

标签: jsonsql-serverssasdynamicquery

解决方案


将 JSON 动态转换为列可能会很棘手。特别是如果您不确定结构。也就是说,您是否考虑过通过 a 将 JSON 转换为层次结构Recursive CTE

例子

declare @json varchar(max)='
[
  {
    "url": "https://www.google.com",
    "image-url": "https://www.google.com/imghp",
    "labels": [
                {
                  "source": "Bob, Inc",
                  "name": "Whips",
                  "info": "Ouch"
                },
                {
                  "source": "Weezles of Oregon",
                  "name": "Chains",
                  "info": "Let me go"
                }
              ],
    "Fact": "Fictional"
  }
]';


;with cte0 as (
   Select *
         ,[Level]=1 
         ,[Path]=convert(varchar(max),row_number() over(order by (select null)))
    From OpenJSON(@json,'$') 
   Union All
   Select R.*
         ,[Level]=p.[Level]+1 
         ,[Path]=concat(P.[Path],'\',row_number() over(order by (select null)))
    From  cte0 p 
    Cross Apply OpenJSON(p.value,'$') R
    Where P.[Type]>3
)
Select [Level]
      ,[Path]
      ,Title = replicate('|---',[Level]-1)+[Key]
      ,Item  = [Key]
      ,Value = case when [type]<4 then Value else null end 
 From cte0
 Order By [Path]

退货

在此处输入图像描述


推荐阅读