SQL Server JSON_VALUE语法

时间:2017-11-08 21:02:46

标签: json sql-server

我创建了一个包含25列的SQL Server表。我的一个列实际上是JSON文本,存储为nvarchar(max)。

现在,我需要能够查询此JSON列并解析各种属性。我已经尝试将JSON_VALUE应用于我的列,但我做错了;我的查询运行但为所有值返回NULL。

JSON本身看起来像:

[ { "lineName":"GHjr", "pipeDiameter":"12", "pipeLength":"52000", "pressure":"15", "volume":"107" }, { "lineName":"Ks3R", "pipeDiameter":"9", "pipeLength":"40000", "pressure":"15", "volume":"80" } ]

我正在使用的SQL是:

select
 DOC_ID, LINE_SPECS,
 JSON_VALUE(LINE_SPECS, '$.lineName')     as line_name,
 JSON_VALUE(LINE_SPECS, '$.pipe_Diameter') as diameter
from dbo.MY_TEST_DOCS
where ISJSON(LINE_SPECS) > 0
  and len(LINE_SPECS) > 3

但是,我的2个“解析”列返回所有NULL。如何解析此列中的五个属性?

1 个答案:

答案 0 :(得分:2)

Without the [] ISJSON is returning false
With [] ISJSON retuns true
Without the [] JSON_VALUE returns NULLs
With [] JSON_VALUE returns values

dbfddle.uk已提供sql server 2016 ....

create table test (LINE_SPECS nvarchar(max));

insert into test values (N'
 {
  "lineName":"GHjr",
  "pipeDiameter":"12",
  "pipeLength":"52000",
  "pressure":"15",
  "volume":"107"
 },
 {
  "lineName":"Ks3R",
  "pipeDiameter":"9",
  "pipeLength":"40000",
  "pressure":"15",
  "volume":"80"
 }
');

select * 
from test
where ISJSON(LINE_SPECS) > 0
;

GO
| LINE_SPECS |
| :--------- |
select
      JSON_VALUE(LINE_SPECS, '$.lineName')     as line_name
    , JSON_VALUE(LINE_SPECS, '$.pipeDiameter') as diameter
from test
;
GO
line_name | diameter
:-------- | :-------
GHjr      | 12      

dbfiddle here