将选择性属性从JSON导入到SQL Server表中的最佳方法是什么

时间:2018-08-23 13:31:48

标签: json sql-server sql-server-2012

我有一个json文件,其中包含需要导入到表中的数据,问题是我只需要LatitudeLongitudepreferredGazzeteerName属性。

这是我的json数据的样子:

[
  {
    "MRGID": 2375,
    "gazetteerSource": "Nomenclature des espaces maritimes/List of maritime areas",
    "placeType": "Strait",
    "latitude": 51.036666666667,
    "longitude": 1.5486111111111,
    "minLatitude": 49.71788333,
    "minLongitude": 0.238905863,
    "maxLatitude": 51.78156033,
    "maxLongitude": 2.744909289,
    "precision": 21000,
    "preferredGazetteerName": "Dover Strait",
    "preferredGazetteerNameLang": "English",
    "status": "standard",
    "accepted": 2375
  },
  {
    "MRGID": 2376,
    "gazetteerSource": "The Times comprehensive atlas of the world. 10th ed. Times Books: London, UK. ISBN 0-7230-0792-6. 67, 220, 124 plates pp.,",
    "placeType": "Strait",
    "latitude": 54.604722222222,
    "longitude": 11.220833333333,
    "minLatitude": null,
    "minLongitude": null,
    "maxLatitude": null,
    "maxLongitude": null,
    "precision": 40000,
    "preferredGazetteerName": "Femer Baelt",
    "preferredGazetteerNameLang": "English",
    "status": "standard",
    "accepted": 2376
  }]

和表enter image description here

preferredGazetteerName值将插入到“海峡名称”列。

1 个答案:

答案 0 :(得分:2)

这是一种使用'{'分隔符分割JSON字符串的方法,而这只是字符串操作的问题

示例

Declare @S varchar(max) ='... your JSON String ...'

Select Name = left(Name,charindex(',',Name+',')-1)
      ,Lat  = try_convert(float,left(Lat,charindex(',',Lat+',')-1))
      ,Lng  = try_convert(float,left(Lng,charindex(',',Lng+',')-1))
 From  (
        Select Name = ltrim(replace(substring(RetVal,nullif(charindex('"preferredGazetteerName"',RetVal),0)+25,75),'"',''))
              ,Lat  = ltrim(substring(RetVal,nullif(charindex('"latitude"',RetVal),0) +11,25))
              ,Lng  = ltrim(substring(RetVal,nullif(charindex('"longitude"',RetVal),0)+12,25))
         From  [dbo].[tvf-Str-Parse](@S,'{') 
       ) A
 Where Name is not null

返回

Name            Lat               Lng
Dover Strait    51.036666666667   1.5486111111111
Femer Baelt     54.604722222222   11.220833333333

感兴趣的拆分/解析TVF

CREATE FUNCTION [dbo].[tvf-Str-Parse] (@String varchar(max),@Delimiter varchar(10))
Returns Table 
As
Return (  
    Select RetSeq = Row_Number() over (Order By (Select null))
          ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
    From  (Select x = Cast('<x>' + replace((Select replace(@String,@Delimiter,'§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A 
    Cross Apply x.nodes('x') AS B(i)
);