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
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
Isaac your code is not working with not quoted values eg {"isAuthorized":"false","customerID":null}. I fixed this and your function should look like this.
ALTER FUNCTION [dbo].[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 @end INT;
set @start = PATINDEX('%' + @column + '":%',@JSON) + LEN(@column) + 2;
SET @trimmedJSON = SUBSTRING(@JSON, @start, LEN(@JSON));
Set @end = CHARINDEX(',',@trimmedJSON);
SET @value = REPLACE(SUBSTRING(@trimmedJSON, 0, @end),'"','');
RETURN @value
END
>>> at JSON_VALUE function, at PATINDEX('%", "%', @trimmedJSON);
remove space from '%", "%'
if your JSON value is like
'{"street":"street1","street2":"street232423"}'
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.