[英]How to parse json data in SQL Server 2012?
I am using SQL Server 2012.I have been assigned a task where one of my column ( JsonText
) of table Sample
contains json data.我正在使用 SQL Server 2012。我被分配了一项任务,其中表Sample
一列( JsonText
)包含 json 数据。 I want to pass parse that data and insert into columns of another table ( Test
).我想通过解析该数据并插入到另一个表( Test
)的列中。 I searched on net 'openjson' is supported in SQL Server 2016. How to do in SQL Server 2012?我在网上搜索 SQL Server 2016 支持“openjson”。如何在 SQL Server 2012 中执行?
Table1 : Sample表 1 : 样品
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.我只对“PID,Address,MobileNumber”列感兴趣,而不是全部。
Table Test structure like this像这样的表测试结构
Id, PID, Address, MobileNumber
I created a function compatible with SQL 2012 to take care of this我创建了一个与 SQL 2012 兼容的函数来处理这个问题
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}.以撒您的代码不能使用未引用的值,例如 {"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如果你的 JSON 值是这样的
'{"street":"street1","street2":"street232423"}'
You can use JSON_VALUE(ColumnName,'$.Path')
for pairs Json in TSQL, for example:您可以将JSON_VALUE(ColumnName,'$.Path')
用于 TSQL 中的 Json 对,例如:
select JSON_VALUE(webaddress,'$.data.PID') as 'PID',
JSON_VALUE(webaddress,'$.data.Status') as 'Status',
JSON_VALUE(webaddress,'$.data.Name') as 'Name'
from test
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.