SQL Server JSON_VALUE 语法

Car*_*Ben 5 sql-server json

我创建了一个包含 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"
 }
]
Run Code Online (Sandbox Code Playgroud)

我使用的 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
Run Code Online (Sandbox Code Playgroud)

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

Use*_*ady 6

Without the [] ISJSON is returning false
With [] ISJSON retuns true
Without the [] JSON_VALUE returns NULLs
With [] JSON_VALUE returns values
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)
| LINE_规格 |
| :--------- |
select
      JSON_VALUE(LINE_SPECS, '$.lineName')     as line_name
    , JSON_VALUE(LINE_SPECS, '$.pipeDiameter') as diameter
from test
;
GO
Run Code Online (Sandbox Code Playgroud)
线路名称 | 直径
:-------- | :--------
GHjr | 12      

dbfiddle在这里