是否有在SQL Server 2014中解析json的解决方案

时间:2019-04-26 05:32:34

标签: json sql-server-2014

我正在尝试将sql Server 2014中存储的json格式的数据更改为如下表:

Id  ImageId     FileNamePath
3    1          9/1/image1.png
3    1          9/1/image2.png  

我在SQL Server 2014中存储了以下JSON(TestImage)

Id  ImagingId   TestImage
3   1           [{"Filename":"9/1/image1.png","OriginalName":"image1.png"}, 
                {"Filename":"9/1/image2.png","OriginalName":"image2.png"}]

我搜索了该网站https://www.red-gate.com/simple-talk/sql/t-sql-programming/consuming-json-strings-in-sql-server/附带的Google以及stackoverflow 创建了parseJSON函数

DECLARE @jsonInfo NVARCHAR(MAX)
select @jsonInfo=TestImage from rptImagings
Select Id, ImageId,
   max(case when name='Text' then convert(Varchar(50),StringValue) else '' 
end) as [Text],
   max(case when name='Value' then convert(Varchar(50),StringValue) else 
'' end) as [Value],
   max(case when name='Default' then convert(bit,StringValue) else 0 end) 
as [Default]
From parseJSON
(
@jsonInfo
)
where ValueType = 'string' OR ValueType = 'boolean'
group by parent_ID

我希望输出结果如下

Id  ImageId     FileNamePath
3    1          9/1/image1.png
3    1          9/1/image2.png

1 个答案:

答案 0 :(得分:0)

这里是将您的JSON转换为XML的一种选择。从那里开始只有一个小问题

需要明确的是,这适用于您的示例数据,但我怀疑将来可能会出现问题。

示例

Declare @YourTable Table ([Id] varchar(50),[ImagingId] varchar(50),[TestImage] varchar(1500))  Insert Into @YourTable Values 
 (3,1,'[{"Filename":"AA/9293/9/1/image1.png","OriginalName":"image1.png"},{"Filename":"AA/9293/9/1/image1.png","OriginalName":"image2.png"}]')

 Select A.ID
       ,A.ImagingId 
       ,C.*
From  YourTable A
Cross Apply ( values(try_convert(xml,replace(replace(replace(replace(replace(replace([TestImage],'[',''),']',''), '":"', '="'),'{"', '<x '),'}','></x>' ), '","','" ')) )) B(XMLData)
Cross Apply (
                Select FileNamePath = xAttr.value('.','varchar(max)')
                 From  XMLData.nodes('//@Filename') xNode(xAttr)
            ) C

返回

ID  ImagingId   FileNamePath
3   1           AA/9293/9/1/image1.png
3   1           AA/9293/9/1/image1.png

更新dbFiddle