为sql server 增加 parseJSON 和 ToJSON 函数
在SqlServer中增加Json处理的方法
Sql Server 存储非结构话数据可以使用xml类型,使用xpath方式查询,以前写过一篇随笔:Sql Server xml 类型字段的增删改查
除了xml类型也可以使用文本类型(char、vchar等)存储json格式的数据,如何在sql语句中解析json数据,这里有一篇博客 [转]在SqlServer 中解析JSON数据,它的来源是Consuming JSON Strings in SQL Server
针对json解析需要一个自定义类型Hierarchy、一个表值函数parseJSON、一个标量值函数ToJSON。语句如下:
/****** Object: UserDefinedTableType [dbo].[Hierarchy] Script Date: 2016/5/6 17:24:48 ******/
CREATE TYPE [dbo].[Hierarchy] AS TABLE(
[element_id] [INT] NOT NULL,
[sequenceNo] [INT] NULL,
[parent_ID] [INT] NULL,
[Object_ID] [INT] NULL,
[NAME] [NVARCHAR]() NULL,
[StringValue] [NVARCHAR](MAX) NOT NULL,
[ValueType] [VARCHAR]() NOT NULL,
PRIMARY KEY CLUSTERED
(
[element_id] ASC
)WITH (IGNORE_DUP_KEY = OFF)
)
GO
Hierarchy
CREATE FUNCTION [dbo].[parseJSON]( @JSON NVARCHAR(MAX))
RETURNS @hierarchy TABLE
(
element_id INT IDENTITY(, ) NOT NULL, /* internal surrogate primary key gives the order of parsing and the list order */
sequenceNo [int] NULL, /* the place in the sequence for the element */
parent_ID INT,/* if the element has a parent then it is in this column. The document is the ultimate parent, so you can get the structure from recursing from the document */
Object_ID INT,/* each list or object has an object id. This ties all elements to a parent. Lists are treated as objects here */
NAME NVARCHAR(),/* the name of the object */
StringValue NVARCHAR(MAX) NOT NULL,/*the string representation of the value of the element. */
ValueType VARCHAR() NOT null /* the declared type of the value represented as a string in StringValue*/
)
AS
BEGIN
DECLARE
@FirstObject INT, --the index of the first open bracket found in the JSON string
@OpenDelimiter INT,--the index of the next open bracket found in the JSON string
@NextOpenDelimiter INT,--the index of subsequent open bracket found in the JSON string
@NextCloseDelimiter INT,--the index of subsequent close bracket found in the JSON string
@Type NVARCHAR(),--whether it denotes an object or an array
@NextCloseDelimiterChar CHAR(),--either a '}' or a ']'
@Contents NVARCHAR(MAX), --the unparsed contents of the bracketed expression
@Start INT, --index of the start of the token that you are parsing
@end INT,--index of the end of the token that you are parsing
@param INT,--the parameter at the end of the next Object/Array token
@EndOfName INT,--the index of the start of the parameter at end of Object/Array token
@token NVARCHAR(),--either a string or object
@value NVARCHAR(MAX), -- the value as a string
@SequenceNo int, -- the sequence number within a list
@name NVARCHAR(), --the name as a string
@parent_ID INT,--the next parent ID to allocate
@lenJSON INT,--the current length of the JSON String
@characters NCHAR(),--used to convert hex to decimal
@result BIGINT,--the value of the hex symbol being parsed
@index SMALLINT,--used for parsing the hex value
@Escape INT --the index of the next escape character DECLARE @Strings TABLE /* in this temporary table we keep all strings, even the names of the elements, since they are 'escaped' in a different way, and may contain, unescaped, brackets denoting objects or lists. These are replaced in the JSON string by tokens representing the string */
(
String_ID INT IDENTITY(, ),
StringValue NVARCHAR(MAX)
)
SELECT--initialise the characters to convert hex to ascii
@characters='0123456789abcdefghijklmnopqrstuvwxyz',
@SequenceNo=, --set the sequence no. to something sensible.
/* firstly we process all strings. This is done because [{} and ] aren't escaped in strings, which complicates an iterative parse. */
@parent_ID=;
WHILE = --forever until there is nothing more to do
BEGIN
SELECT
@start=PATINDEX('%[^a-zA-Z]["]%', @json collate SQL_Latin1_General_CP850_Bin);--next delimited string
IF @start= BREAK --no more so drop through the WHILE loop
IF SUBSTRING(@json, @start+, )='"'
BEGIN --Delimited Name
SET @start=@Start+;
SET @end=PATINDEX('%[^\]["]%', RIGHT(@json, LEN(@json+'|')-@start) collate SQL_Latin1_General_CP850_Bin);
END
IF @end= --no end delimiter to last string
BREAK --no more
SELECT @token=SUBSTRING(@json, @start+, @end-)
--now put in the escaped control characters
SELECT @token=REPLACE(@token, FROMString, TOString)
FROM
(SELECT
'\"' AS FromString, '"' AS ToString
UNION ALL SELECT '\\', '\'
UNION ALL SELECT '\/', '/'
UNION ALL SELECT '\b', CHAR()
UNION ALL SELECT '\f', CHAR()
UNION ALL SELECT '\n', CHAR()
UNION ALL SELECT '\r', CHAR()
UNION ALL SELECT '\t', CHAR()
) substitutions
SELECT @result=, @escape=
--Begin to take out any hex escape codes
WHILE @escape>
BEGIN
SELECT @index=,
--find the next hex escape sequence
@escape=PATINDEX('%\x[0-9a-f][0-9a-f][0-9a-f][0-9a-f]%', @token collate SQL_Latin1_General_CP850_Bin)
IF @escape> --if there is one
BEGIN
WHILE @index< --there are always four digits to a \x sequence
BEGIN
SELECT --determine its value
@result=@result+POWER(, @index)
*(CHARINDEX(SUBSTRING(@token, @escape++-@index, ),
@characters)-), @index=@index+ ; END
-- and replace the hex sequence by its unicode value
SELECT @token=STUFF(@token, @escape, , NCHAR(@result))
END
END
--now store the string away
INSERT INTO @Strings (StringValue) SELECT @token
-- and replace the string with a token
SELECT @JSON=STUFF(@json, @start, @end+,
'@string'+CONVERT(NVARCHAR(), @@identity))
END
-- all strings are now removed. Now we find the first leaf.
WHILE = --forever until there is nothing more to do
BEGIN SELECT @parent_ID=@parent_ID+
--find the first object or list by looking for the open bracket
SELECT @FirstObject=PATINDEX('%[{[[]%', @json collate SQL_Latin1_General_CP850_Bin)--object or array
IF @FirstObject = BREAK
IF (SUBSTRING(@json, @FirstObject, )='{')
SELECT @NextCloseDelimiterChar='}', @type='object'
ELSE
SELECT @NextCloseDelimiterChar=']', @type='array'
SELECT @OpenDelimiter=@firstObject WHILE = --find the innermost object or list...
BEGIN
SELECT
@lenJSON=LEN(@JSON+'|')-
--find the matching close-delimiter proceeding after the open-delimiter
SELECT
@NextCloseDelimiter=CHARINDEX(@NextCloseDelimiterChar, @json,
@OpenDelimiter+)
--is there an intervening open-delimiter of either type
SELECT @NextOpenDelimiter=PATINDEX('%[{[[]%',
RIGHT(@json, @lenJSON-@OpenDelimiter)COLLATE SQL_Latin1_General_CP850_Bin)--object
IF @NextOpenDelimiter=
BREAK
SELECT @NextOpenDelimiter=@NextOpenDelimiter+@OpenDelimiter
IF @NextCloseDelimiter<@NextOpenDelimiter
BREAK
IF SUBSTRING(@json, @NextOpenDelimiter, )='{'
SELECT @NextCloseDelimiterChar='}', @type='object'
ELSE
SELECT @NextCloseDelimiterChar=']', @type='array'
SELECT @OpenDelimiter=@NextOpenDelimiter
END
---and parse out the list or name/value pairs
SELECT
@contents=SUBSTRING(@json, @OpenDelimiter+,
@NextCloseDelimiter-@OpenDelimiter-)
SELECT
@JSON=STUFF(@json, @OpenDelimiter,
@NextCloseDelimiter-@OpenDelimiter+,
'@'+@type+CONVERT(NVARCHAR(), @parent_ID))
WHILE (PATINDEX('%[A-Za-z0-9@+.e]%', @contents COLLATE SQL_Latin1_General_CP850_Bin))<>
BEGIN
IF @Type='Object' --it will be a -n list containing a string followed by a string, number,boolean, or null
BEGIN
SELECT
@SequenceNo=,@end=CHARINDEX(':', ' '+@contents)--if there is anything, it will be a string-based name.
SELECT @start=PATINDEX('%[^A-Za-z@][@]%', ' '+@contents COLLATE SQL_Latin1_General_CP850_Bin)--AAAAAAAA
SELECT @token=SUBSTRING(' '+@contents, @start+, @End-@Start-),
@endofname=PATINDEX('%[0-9]%', @token COLLATE SQL_Latin1_General_CP850_Bin),
@param=RIGHT(@token, LEN(@token)-@endofname+)
SELECT
@token=LEFT(@token, @endofname-),
@Contents=RIGHT(' '+@contents, LEN(' '+@contents+'|')-@end-)
SELECT @name=stringvalue FROM @strings
WHERE string_id=@param --fetch the name
END
ELSE
SELECT @Name=NULL,@SequenceNo=@SequenceNo+
SELECT
@end=CHARINDEX(',', @contents)-- a string-token, object-token, list-token, number,boolean, or null
IF @end=
SELECT @end=PATINDEX('%[A-Za-z0-9@+.e][^A-Za-z0-9@+.e]%', @Contents+' ' COLLATE SQL_Latin1_General_CP850_Bin)
+
SELECT
@start=PATINDEX('%[^A-Za-z0-9@+.e][A-Za-z0-9@+.e]%', ' '+@contents COLLATE SQL_Latin1_General_CP850_Bin)
--select @start,@end, LEN(@contents+'|'), @contents
SELECT
@Value=RTRIM(SUBSTRING(@contents, @start, @End-@Start)),
@Contents=RIGHT(@contents+' ', LEN(@contents+'|')-@end)
IF SUBSTRING(@value, , )='@object'
INSERT INTO @hierarchy
(NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)
SELECT @name, @SequenceNo, @parent_ID, SUBSTRING(@value, , ),
SUBSTRING(@value, , ), 'object'
ELSE
IF SUBSTRING(@value, , )='@array'
INSERT INTO @hierarchy
(NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)
SELECT @name, @SequenceNo, @parent_ID, SUBSTRING(@value, , ),
SUBSTRING(@value, , ), 'array'
ELSE
IF SUBSTRING(@value, , )='@string'
INSERT INTO @hierarchy
(NAME, SequenceNo, parent_ID, StringValue, ValueType)
SELECT @name, @SequenceNo, @parent_ID, stringvalue, 'string'
FROM @strings
WHERE string_id=SUBSTRING(@value, , )
ELSE
IF @value IN ('true', 'false')
INSERT INTO @hierarchy
(NAME, SequenceNo, parent_ID, StringValue, ValueType)
SELECT @name, @SequenceNo, @parent_ID, @value, 'boolean'
ELSE
IF @value='null'
INSERT INTO @hierarchy
(NAME, SequenceNo, parent_ID, StringValue, ValueType)
SELECT @name, @SequenceNo, @parent_ID, @value, 'null'
ELSE
IF PATINDEX('%[^0-9]%', @value COLLATE SQL_Latin1_General_CP850_Bin)>
INSERT INTO @hierarchy
(NAME, SequenceNo, parent_ID, StringValue, ValueType)
SELECT @name, @SequenceNo, @parent_ID, @value, 'real'
ELSE
INSERT INTO @hierarchy
(NAME, SequenceNo, parent_ID, StringValue, ValueType)
SELECT @name, @SequenceNo, @parent_ID, @value, 'int'
IF @Contents=' ' SELECT @SequenceNo=
END
END
INSERT INTO @hierarchy (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)
SELECT '-',, NULL, '', @parent_id-, @type
--
RETURN
END
parseJSON
/****** Object: UserDefinedFunction [dbo].[ToJSON] Script Date: 2016/5/6 17:25:49 ******/
SET ANSI_NULLS ON
GO SET QUOTED_IDENTIFIER ON
GO CREATE FUNCTION [dbo].[ToJSON]
(
@Hierarchy Hierarchy READONLY
) /*
the function that takes a Hierarchy table and converts it to a JSON string Author: Phil Factor
Revision: 1.5
date: 1 May 2014
why: Added a fix to add a name for a list.
example: Declare @XMLSample XML
Select @XMLSample='
<glossary><title>example glossary</title>
<GlossDiv><title>S</title>
<GlossList>
<GlossEntry ID="SGML" SortAs="SGML">
<GlossTerm>Standard Generalized Markup Language</GlossTerm>
<Acronym>SGML</Acronym>
<Abbrev>ISO 8879:1986</Abbrev>
<GlossDef>
<para>A meta-markup language, used to create markup languages such as DocBook.</para>
<GlossSeeAlso OtherTerm="GML" />
<GlossSeeAlso OtherTerm="XML" />
</GlossDef>
<GlossSee OtherTerm="markup" />
</GlossEntry>
</GlossList>
</GlossDiv>
</glossary>' DECLARE @MyHierarchy Hierarchy -- to pass the hierarchy table around
insert into @MyHierarchy select * from dbo.ParseXML(@XMLSample)
SELECT dbo.ToJSON(@MyHierarchy) */
RETURNS NVARCHAR(MAX)--JSON documents are always unicode.
AS
BEGIN
DECLARE
@JSON NVARCHAR(MAX),
@NewJSON NVARCHAR(MAX),
@Where INT,
@ANumber INT,
@notNumber INT,
@indent INT,
@ii INT,
@CrLf CHAR()--just a simple utility to save typing! --firstly get the root token into place
SELECT @CrLf=CHAR()+CHAR(),--just CHAR() in UNIX
@JSON = CASE ValueType WHEN 'array' THEN
+COALESCE('{'+@CrLf+' "'+NAME+'" : ','')+'['
ELSE '{' END
+@CrLf
+ CASE WHEN ValueType='array' AND NAME IS NOT NULL THEN ' ' ELSE '' END
+ '@Object'+CONVERT(VARCHAR(),OBJECT_ID)
+@CrLf+CASE ValueType WHEN 'array' THEN
CASE WHEN NAME IS NULL THEN ']' ELSE ' ]'+@CrLf+'}'+@CrLf END
ELSE '}' END
FROM @Hierarchy
WHERE parent_id IS NULL AND valueType IN ('object','document','array') --get the root element
/* now we simply iterat from the root token growing each branch and leaf in each iteration. This won't be enormously quick, but it is simple to do. All values, or name/value pairs withing a structure can be created in one SQL Statement*/
SELECT @ii=
WHILE @ii>
BEGIN
SELECT @where= PATINDEX('%[^[a-zA-Z0-9]@Object%',@json)--find NEXT token
IF @where= BREAK
/* this is slightly painful. we get the indent of the object we've found by looking backwards up the string */
SET @indent=CHARINDEX(CHAR()+CHAR(),REVERSE(LEFT(@json,@where))+CHAR()+CHAR())-
SET @NotNumber= PATINDEX('%[^0-9]%', RIGHT(@json,LEN(@JSON+'|')-@Where-)+' ')--find NEXT token
SET @NewJSON=NULL --this contains the structure in its JSON form
SELECT
@NewJSON=COALESCE(@NewJSON+','+@CrLf+SPACE(@indent),'')
+CASE WHEN parent.ValueType='array' THEN '' ELSE COALESCE('"'+TheRow.NAME+'" : ','') END
+CASE TheRow.valuetype
WHEN 'array' THEN ' ['+@CrLf+SPACE(@indent+)
+'@Object'+CONVERT(VARCHAR(),TheRow.[OBJECT_ID])+@CrLf+SPACE(@indent+)+']'
WHEN 'object' THEN ' {'+@CrLf+SPACE(@indent+)
+'@Object'+CONVERT(VARCHAR(),TheRow.[OBJECT_ID])+@CrLf+SPACE(@indent+)+'}'
WHEN 'string' THEN '"'+dbo.JSONEscaped(TheRow.StringValue)+'"'
ELSE TheRow.StringValue
END
FROM @Hierarchy TheRow
INNER JOIN @hierarchy Parent
ON parent.element_ID=TheRow.parent_ID
WHERE TheRow.parent_id= SUBSTRING(@JSON,@where+, @Notnumber-)
/* basically, we just lookup the structure based on the ID that is appended to the @Object token. Simple eh? */
--now we replace the token with the structure, maybe with more tokens in it.
SELECT @JSON=STUFF (@JSON, @where+, +@NotNumber-, @NewJSON),@ii=@ii-
END
RETURN @JSON
END GO
toJson
在Sql查询中使用parseJSON和toJson方法
Sql Server xml 类型字段的增删改查 文章中介绍了几种用法,我这里非常简单。有一张表 Candidate_Ext,CVParseJson 字段存储了json格式数据,其中有个节点是SkillName存储了技能列表,这里使用sql语句把技能名称查出来逗号分隔。
"SkillList": [
{
"SkillId": ,
"CandidateId": ,
"TenantId": ,
"SkillName": "Oracle",
"SkillLevel": ,
"SkillLevelName": "熟练",
"SkillLevelName1": null
},
{
"SkillId": ,
"CandidateId": ,
"TenantId": ,
"SkillName": "TCP/IP",
"SkillLevel": ,
"SkillLevelName": "精通",
"SkillLevelName1": null
}
],
sql语句:
SELECT TOP l.CandidateId ,l.CVParseJson,
( SELECT StringValue+','
FROM parseJSON(l.CVParseJson) json
WHERE json.NAME='SkillName'
FOR
XML PATH('')
) 专业技能
FROM dbo.Candidate_Ext l
WHERE CVParseJson LIKE '{"candi%'
结果:
CandidateId 专业技能
Oracle,TCP/IP,
如果多个节点都有SkillName 这个属性处理起来就比较麻烦了,性能也不见得好,所以小数据出来使用这个方法还是比较方便的。
为sql server 增加 parseJSON 和 ToJSON 函数的更多相关文章
- SQL SERVER中用户定义标量函数(scalar user defined function)的性能问题
用户定义函数(UDF)分类 SQL SERVER中的用户定义函数(User Defined Functions 简称UDF)分为标量函数(Scalar-Valued Function)和表值函数(T ...
- SQL Server利用RowNumber()内置函数与Over关键字实现通用分页存储过程(支持单表或多表结查集分页)
SQL Server利用RowNumber()内置函数与Over关键字实现通用分页存储过程,支持单表或多表结查集分页,存储过程如下: /******************/ --Author:梦在旅 ...
- (转载)MS SQL Server 未公开的加密函数有哪些?
MS SQL Server 未公开的加密函数有哪些? 以下的文章是对MS SQL Server 未公开的加密函数的具体操作,如果你对其相关的实际操作有兴趣的话,你就可以点击了. MS SQL Serv ...
- SQL Server如何定位自定义标量函数被那个SQL调用次数最多浅析
前阵子遇到一个很是棘手的问题,监控系统DPA发现某个自定义标量函数被调用的次数非常高,高到一个离谱的程度.然后在Troubleshooting这个问题的时候,确实遇到了一些问题让我很是纠结,下文是解决 ...
- Sql Server 增加字段、修改字段、修改类型、修改默认值(转)
转:http://www.cnblogs.com/pangpanghuan/p/6432331.html Sql Server 增加字段.修改字段.修改类型.修改默认值 1.修改字段名: alter ...
- SQL SERVER 提供了一些时间函数:
SQL SERVER 提供了一些时间函数:取当前时间:select getdate()取前一个月的时间:SELECT DATEADD(MONTH,-1,GETDATE()) 月份减一个月取年份:SEL ...
- 深入理解SQL Server 2005 中的 COLUMNS_UPDATED函数
原文:深入理解SQL Server 2005 中的 COLUMNS_UPDATED函数 概述 COLUMNS_UPDATED函数能够出现在INSERT或UPDATE触发器中AS关键字后的任何位置,用来 ...
- SQL Server 2019 中标量用户定义函数性能的改进
在SQL Server中,我们通常使用用户定义的函数来编写SQL查询.UDF接受参数并将结果作为输出返回.我们可以在编程代码中使用这些UDF,并且可以快速编写查询.我们可以独立于任何其他编程代码来修改 ...
- SQL Server系统表和常用函数(转)
sysaltfiles 主数据库 保存数据库的文件 syscharsets 主数据库 字符集与排序顺序sysconfigures 主数据库 配置选项syscurconfigs 主数据库 当前配置选项s ...
随机推荐
- Unity3D使用经验总结 优点篇
09年还在和其它小伙伴开发引擎的时候,Unity3D就初露头角. 当时就对这种基于组件式的设计结构很不理解. 觉得拆分过于细致,同时影响效率. 而时至今日,UNITY3D已经成为了众多团队的首选3D引 ...
- zend studio 常用快捷键
zend studio是一款很棒的PHP语言编译器,强大的功能让很多程序员爱不释手,而快捷键更是程序员加快编写代码的利器,那么一起来看看有哪些好用的快捷键吧. 复制当前行:ctrl+alt+↓ 删除当 ...
- Redmine与Windows AD集成设置
Redmine的账号支持跟LDAP集成,以下是在WINDOWS AD账号的集成配置过程. 首先下载一个微软的dsquery.exe工具,用来查询自己的账户信息. C:\WINDOWS>dsque ...
- Node.js与Sails~中间查询语言Waterline
回到目录 上讲主要说了如何配置sails的持久化机制,这讲主要说一下实现持久化时的增删改查的语法,在sails里使用了和mongodb风格类似的waterline查询语言,使用简单,语法生动,下面我们 ...
- Atitit 图像处理知识点 知识体系 知识图谱
Atitit 图像处理知识点 知识体系 知识图谱 图像处理知识点 图像处理知识点体系 v2 qb24.xlsx 基本知识图像金字塔op膨胀叠加混合变暗识别与检测分类肤色检测other验证码生成 基本 ...
- Atitti 数据库事务处理 attilax总结
Atitti 数据库事务处理 attilax总结 1.1. 为什么要传递Connection?1 1.2. 两种事务处理方式,一种是编程式事务处理;一种是声明...2 1.3. 事务隔离级别 2 1. ...
- Tomcat源码解读系列(一)——server.xml文件的配置
Tomcat是J2EE开发人员最常用到的开发工具,在Java Web应用的调试开发和实际部署中,我们都可以看到Tomcat的影子.大多数时候,我们可以将Tomcat当做一个黑盒来看待,只需要将编写的J ...
- Liferay7 BPM门户开发之45: 集成Activiti文件上传部署流程BPMN模型
开发文件上传,部署流程模板. 首先,开发jsp页面,deploy.jsp <%@ include file="/init.jsp" %> <h3>${RET ...
- Mongodb安装与配置详解
简介: mongodb作为一款通用型数据库,除了能够创建,读取,更新和删除数据外,还提供一系列不断扩展的独特功能. a.索引: mongodb支持二级索引,允许多种快速查询,且提供和唯一索引,复合索引 ...
- MYSQL数据表建立外键
MySQL创建关联表可以理解为是两个表之间有个外键关系,但这两个表必须满足三个条件1.两个表必须是InnoDB数据引擎2.使用在外键关系的域必须为索引型(Index)3.使用在外键关系的域必须与数据类 ...