How to parse json data in SQL Server 2012?

和自甴很熟 提交于 2019-12-25 06:08:24

问题


I am using SQL Server 2012.I have been assigned a task where one of my column (JsonText) of table Sample contains json data. I want to pass parse that data and insert into columns of another table (Test). I searched on net 'openjson' is supported in SQL Server 2016. How to do in SQL Server 2012?

Table1 : Sample

Id JsonText Active 

JsonText

webaddress?{'data':'{"PId": "XXXX","Status": "YES","Name":"XXX","Address":"XXXX","MobileNumber":"xxx"}'}

I am intrested only 'PID,Address,MobileNumber' columns not all.

Table Test structure like this

Id, PID, Address, MobileNumber

回答1:


I created a function compatible with SQL 2012 to take care of this

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Isaac Adams
-- Create date: 7/12/2018
-- Description: Give the JSON string and the name of the column from which you want the value
-- =============================================
CREATE FUNCTION JSON_VALUE
(
    @JSON NVARCHAR(3000),
    @column NVARCHAR(3000)
)
RETURNS NVARCHAR(3000)
AS
BEGIN

DECLARE @value NVARCHAR(3000);
DECLARE @trimmedJSON NVARCHAR(3000);

DECLARE @start INT;
DECLARE @length INT;

SET @start = PATINDEX('%' + @column + '":"%',@JSON) + LEN(@column) + 3;
SET @trimmedJSON = SUBSTRING(@JSON, @start, LEN(@JSON));
SET @length = PATINDEX('%", "%', @trimmedJSON);
SET @value = SUBSTRING(@trimmedJSON, 0, @length);

RETURN @value
END
GO



回答2:


You can use JSON_VALUE(ColumnName,'$.Path') for pairs Json in TSQL, for example:

select JSON_VALUE(webaddress,'$.data.PID') as 'PID',
       JSON_VALUE(webaddress,'$.data.Status') as 'Status',
       JSON_VALUE(webaddress,'$.data.Name') as 'Name'
from test


来源:https://stackoverflow.com/questions/41094989/how-to-parse-json-data-in-sql-server-2012

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!