为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 ...
随机推荐
- 自制C#版3DS文件的解析器并用SharpGL显示3DS模型
自制C#版3DS文件的解析器并用SharpGL显示3DS模型 我已经重写了3ds解析器,详情在此(http://www.cnblogs.com/bitzhuwei/p/CSharpGL-2-parse ...
- redis中使用java脚本实现分布式锁
转载于:http://www.itxuexiwang.com/a/shujukujishu/redis/2016/0216/115.html?1455860390 edis被大量用在分布式的环境中,自 ...
- Bootstrap~日期控制
回到目录 一个成熟的框架,日期控制是少不了的,在网上也有很多日期控制可以选择,而主框架用了bootstrap,日期控制也当前要用它自己的, 控件地址:http://www.bootcss.com/p/ ...
- MVVM架构~knockoutjs与MVC配合,实现列表的增删改功能
返回目录 MVC与MVVM的模型 在MVC实例项目中,为我们提供了简单的增删改查功能,而这种功能的实现与具体的Model很有关系,或者说它与后台数据库的关系过于紧密了,而对于开发人员来说当页面布局修改 ...
- js常用函数
日期时间函数(需要用变量调用): var c=new Date; c.getDate(); document.write(c) //获取当前时间 var c=new Date(); c.getTime ...
- salesforce 零基础学习(三十四)动态的Custom Label
custom label在项目中经常用到,常用在apex class或者VF里面用来显示help text或者error message.有的时候我们需要用到的信息是动态变化的,那样就需要动态来显示信 ...
- iOS-性能优化2
性能优化总结2 iOS应用是非常注重用户体验的,不光是要求界面设计合理美观,也要求各种UI的反应灵敏,我相信大家对那种一拖就卡卡卡的 TableView 应用没什么好印象.还记得12306么,那个速度 ...
- CCNA网络工程师学习进程(1)网络的基本概述
在互联网快速发展的今天,了解互联网成为一项必须的技能,因此在学习编程之余学习如何配置网络还是很有必要的. 本系列博客计划分为三个部分,包括思科CCNA.CCNP和华为的网络工程师认证有关的知识 ...
- wangEditor——轻量级web富文本框
提示:最新版wangEditor请参见 http://www.wangeditor.com/ 和 https://github.com/wangfupeng1988/wangEditor 交流 ...
- CSS 框模型( Box module )
框和布局 在 KB005: CSS 层叠 中已经介绍了 CSS 的重要之处.CSS 可以说是页面表现的基础, CSS 可以控制布局,控制元素的渲染. 布局是讲在电影画面构图中,对环境的布置.人物地位的 ...