SQL get JSOn字符串值列以number开头

时间:2017-05-03 16:26:24

标签: sql sql-server json tsql

如何获取以Number开头的列值。例如:

DECLARE @Text NVARCHAR(MAX) = '{      "1Property1" :"shiva",     "Property2" :"here ",     "metadata-department": "A",     "metadata-group": "B" }'; 

此处属性名称以数字1开头。

我需要一个在sql server中获取价值的解决方案

2 个答案:

答案 0 :(得分:0)

获取delimitedSplit8K的副本,您可以这样做:

DECLARE @Text NVARCHAR(MAX) = '{      "1Property1" :"shiva",     "Property2" :"here ",     "metadata-department": "A",     "metadata-group": "B" }';

SELECT Item
FROM dbo.DelimitedSplit8K(@Text, '"')
WHERE Item LIKE '[0-9][a-zA-Z]%';

结果:

Item
-----------
1Property1

根据您的回复快速更新

我目前没有SQL 2016框,所以我不能使用JSON_VALUE。以下是可以帮助您的Microsoft页面:JSON Data (SQL Server)。下面是一个很好的SQL 2016之前的解决方案,用于获取所有列名和相关字段:

DECLARE @Text NVARCHAR(MAX) = 
  '{      "1Property1" :"shiva",     "Property2" :"here ",     "metadata-department": "A",     "metadata-group": "B" }';

WITH 
split1 AS
(
  SELECT Item = REPLACE(REPLACE(Item, '}', ''), '"', '')
  FROM dbo.DelimitedSplit8K_2012(SUBSTRING(@Text, CHARINDEX('"', @Text), 10000), ',')
),
split2 AS
(
  SELECT
    s1.Item, 
    ColName = MAX(CASE ItemNumber WHEN 1 THEN s2.item END),
    ColVal  = MAX(CASE ItemNumber WHEN 2 THEN s2.item END)
  FROM split1 s1
  CROSS APPLY dbo.DelimitedSplit8K_2012(s1.Item, ':') s2
  GROUP BY s1.Item
)
SELECT 
  ColName = LTRIM(RTRIM(ColName)),
  ColVal  = LTRIM(RTRIM(colVal))
FROM split2;

结果:

ColName              ColVal
-------------------- ------
metadata-department  A
metadata-group       B
Property2            here
1Property1           shiva

要获得“列”以数字开头的那个,您将包括:

WHERE colname LIKE '[0-9]%';

答案 1 :(得分:0)

如果您有SQL Server 2016,请使用:

SELECT Value
FROM OPENJSON(@Text) 
WHERE [Key] = '1Property1'