sql与nosql

In this article, we will explain what JSON is, what are the SQL Server JSON functions introduced in 2016, how to index JSON values, and how to import JSON data into SQL tables.

在本文中,我们将解释什么是JSON,2016年引入SQL Server JSON函数是什么,如何索引JSON值以及如何将JSON数据导入SQL表。

介绍 (Introduction)

JavaScript Object Notation (JSON) is an open universal data format that uses human-readable text to store data objects in a map format (Key/value pairs). This object notation was standardized in 2013 as ECMA-404. Many years ago, JSON was not popular, while XML was widely used in the data exchange operations. With the rise of the Big Data and NoSQL notions, JSON started slowly to replace XML since it is used and supported by the new data technologies.

的J ava 小号 CRIPTöbjectÑ浮选(JSON)是使用人类可读的文本来存储数据以地图格式(键/值对)对象的开放通用数据格式。 该对象表示法于2013年标准化为ECMA-404 。 许多年前,JSON不流行,而XML被广泛用于数据交换操作中。 随着大数据和NoSQL概念的兴起,JSON开始慢慢取代XML,因为新数据技术已使用并支持它。

Since companies and data consumers widely use traditional database management systems, these systems’ providers started supporting the new data technologies and features to keep pace with their customers emerging needs.

由于公司和数据消费者广泛使用传统的数据库管理系统,因此这些系统的提供商开始支持新的数据技术和功能,以与客户的新兴需求保持同步。

Regarding SQL Server, starting with the 2012 release, the database engine is not considered anymore for medium scale enterprises after adding high-end data-center management capabilities. In the 2016 version, Polybase was introduced, adding the ability to connect traditional databases with NoSQL databases and Hadoop data lakes (more capabilities were introduced in 2019 such as MongoDB and Oracle database support). Besides, JSON becomes supported, enabling developers to combine NoSQL and relational concepts by storing documents formatted as JSON text within tables storing traditional data.

对于SQL Server,从2012版本开始,在添加高端数据中心管理功能之后,中型企业不再考虑使用数据库引擎。 在2016版中,引入了Polybase,增加了连接传统数据库与NoSQL数据库和Hadoop数据湖的功能(2019年引入了更多功能,例如MongoDB和Oracle数据库支持)。 此外,JSON受到支持,使开发人员可以通过将格式为JSON文本的文档存储在存储传统数据的表中,从而将NoSQL和关系概念结合起来。

In the following sections, we will explain SQL Server JSON functions and how to index JSON values and import JSON data into SQL.

在以下各节中,我们将说明SQL Server JSON函数以及如何索引JSON值以及如何将JSON数据导入SQL。

SQL Server JSON函数 (SQL Server JSON functions)

Based on the official Microsoft documentation, the added JSON functionalities allows developers to:

根据Microsoft的官方文档 ,添加的JSON功能使开发人员能够:

  1. Parse JSON text and read or modify values 解析JSON文本并读取或修改值
  2. Transform arrays of JSON objects into table format 将JSON对象数组转换为表格格式
  3. Run any Transact-SQL query on the converted JSON objects 在转换后的JSON对象上运行任何Transact-SQL查询
  4. Format the results of Transact-SQL queries in JSON format 以JSON格式格式化Transact-SQL查询的结果

In this section, we will explain each functionality added by providing some examples using the AdventureWorks database. Before describing these functionalities, we will create a new field of type NVARCHAR(MAX) within the [Person].[Person] table to be used during this guide.

在本节中,我们将通过使用AdventureWorks数据库提供一些示例来说明添加的每个功能。 在描述这些功能之前,我们将在[Person]。[Person]表中创建一个类型为NVARCHAR(MAX)的新字段,以在本指南中使用。

FOR JSON子句 (FOR JSON clause)

This clause is used to convert tabular data into a JSON text. There are two options to be used within this clause:

此子句用于将表格数据转换为JSON文本。 此子句中使用两个选项:

  1. FOR JSON PATH: to format and configure the output JSON text manually FOR JSON PATH:手动设置格式和配置输出JSON文本
  2. FOR JSON AUTO: to format the output JSON text automatically FOR JSON AUTO:自动设置输出JSON文本的格式

In this guide, we will use the second option to generate JSON text. As an example, let’s convert a record from the Person table to a JSON text:

在本指南中,我们将使用第二个选项来生成JSON文本。 例如,让我们将记录从Person表转换为JSON文本:

 SELECT TOP 1 [BusinessEntityID]
,[PersonType]
,[NameStyle]
,[Title]
,[FirstName]
,[MiddleName]
,[LastName]
,[Suffix]
,[EmailPromotion]
,[AdditionalContactInfo]
,[Demographics]
,[rowguid]
,[ModifiedDate]
FROM [AdventureWorks2017].[Person].[Person]
FOR JSON AUTO

The result will be shown as following:

结果将显示如下:

To continue our experiments, we will fill the newly added NVARCHAR(MAX) column (called Details) with the JSON text created from the other columns using the following query:

为了继续我们的实验,我们将使用从其他列创建的JSON文本(使用以下查询)填充新添加的NVARCHAR(MAX)列(称为Details)

UPDATE [AdventureWorks2017].[Person].[Person]
SET [Details] = (SELECT [BusinessEntityID]
,[PersonType]
,[NameStyle]
,[Title]
,[FirstName]
,[MiddleName]
,[LastName]
,[Suffix]
,[EmailPromotion]
,[AdditionalContactInfo]
,[Demographics]
,[rowguid]
,[ModifiedDate]
FROM [AdventureWorks2017].[Person].[Person] T1
WHERE T1.[BusinessEntityID] = [AdventureWorks2017].[Person].[Person].[BusinessEntityID] FOR JSON AUTO)

If you decided to go with the first option we mentioned (FOR JSON PATH), you can refer to the following official documentation.

如果您决定采用我们提到的第一个选项(FOR JSON PATH),则可以参考以下官方文档 。

ISJSON()函数 (ISJSON() function)

ISJSON() is the simplest SQL Server JSON function; it checks if a given string is a valid JSON text. It returns 1 if the string is valid, else it returns 0.

ISJSON()是最简单SQL Server JSON函数; 它检查给定的字符串是否是有效的JSON文本。 如果字符串有效,则返回1 ,否则返回0

As an example, we will use check if FirstName and Details (the added NVARCHAR(MAX) column) columns contain a valid JSON text:

作为示例,我们将使用FirstNameDetails (添加的NVARCHAR(MAX)列)列是否包含有效的JSON文本:

SELECT TOP 1 ISJSON([FirstName]) IsJson_FirstName,ISJSON([Details]) IsJson_Details
FROM [AdventureWorks2017].[Person].[Person]

As shown in the image below, FirstName does not contain a valid JSON while Details does.

如下图所示, FirstName不包含有效的JSON,而Details则包含。

JSON_VALUE()函数 (JSON_VALUE() function)

To extract a scalar value from a JSON text, we can use JSON_VALUE() function. This SQL Server JSON function takes the input JSON string and the JSON path that contains the property to extract as arguments. (Note that the context item of a JSON path is a dollar sign ($).)

要从JSON文本提取标量值,我们可以使用JSON_VALUE()函数。 此SQL Server JSON函数采用输入的JSON字符串和包含要提取的属性的JSON路径作为参数。 ( 请注意,JSON路径的上下文项是美元符号($)。)

In the following example, we used JSON_VALUE() function to filter the query result where the BusinessEntityID value stored within the first array of the JSON text is equal to 1:

在以下示例中,我们使用JSON_VALUE()函数筛选查询结果,其中JSON文本的第一个数组中存储的BusinessEntityID值等于1:

SELECT *
FROM [AdventureWorks2017].[Person].[Person]
WHERE JSON_VALUE([Details], '$[0].BusinessEntityID') = '1'

As shown below, the query returns only one row:

如下所示,查询仅返回一行:

More examples of the JSON_VALUE() function can be found in the official documentation.

JSON_VALUE()函数的更多示例可以在官方文档中找到。

Besides, if you are not familiar with JSON PATH expressions, you can refer to the following article.

此外,如果您不熟悉JSON PATH表达式,则可以参考以下文章 。

JSON_QUERY()函数 (JSON_QUERY() function)

To extract an array or object from a JSON text, we must use JSON_QUERY() function. This SQL Server JSON function is similar to JSON_VALUE(); it takes the same arguments (input JSON and path) and returns a JSON text (NVARCHAR(MAX)) value.

要从JSON文本提取数组或对象,我们必须使用JSON_QUERY()函数。 此SQL Server JSON函数类似于JSON_VALUE(); 它采用相同的参数(输入JSON和路径),并返回JSON文本(NVARCHAR(MAX))值。

As an example, let’s return the items stored within the first array in the root element:

例如,让我们返回根元素中第一个数组中存储的项目:

SELECT TOP 5 JSON_Query([Details], '$[0]')
FROM [AdventureWorks2017].[Person].[Person]

As shown in the image below, the result is a JSON string.

如下图所示,结果是一个JSON字符串。

JSON_MODIFY()函数 (JSON_MODIFY() function)

This function modifies the value of a property within a JSON string and returns the updated JSON text. It takes three parameters; the input JSON string, the property JSON path, and the new value. As an example, If we are looking to add a leading zero to the BusinessEntityID property stored within the Details column. We should use the following query:

此函数修改JSON字符串中的属性值,并返回更新的JSON文本。 它包含三个参数; 输入JSON字符串,属性JSON路径和新值。 例如,如果我们要向“ 详细信息”列中存储的BusinessEntityID属性添加前导零。 我们应该使用以下查询:

UPDATE [AdventureWorks2017].[Person].[Person]
SET [Details] = JSON_MODIFY([Details],'$[0].BusinessEntityID','0' + JSON_VALUE([Details], '$[0].BusinessEntityID'))

Now if we execute the query we provided in the JSON_VALUE() function section, it will not retun any result until we add a leading zero to the condition:

现在,如果我们执行在JSON_VALUE()函数部分中提供的查询,它将不会重新调整任何结果,除非我们向条件添加前导零:

SELECT *
FROM [AdventureWorks2017].[Person].[Person]
WHERE JSON_VALUE([Details], '$[0].BusinessEntityID') = '01'

The following image shows the result of this query:

下图显示了此查询的结果:

OPENJSON()函数 (OPENJSON() function)

If you are looking to parse a JSON text into a key-value pairs or a tabular data, you can use OPENJSON() table-valued function. To convert a JSON string to a key-value pair we must use OPENJSON() function as follows:

如果您希望将JSON文本解析为键值对或表格数据,则可以使用OPENJSON()表值函数。 要将JSON字符串转换为键值对,我们必须使用OPENJSON()函数,如下所示:

DECLARE @json nvarchar(max)
SELECT @json = JSON_QUERY([Details],'$[0]') from [AdventureWorks2017].[Person].[Person] WHERE JSON_VALUE([Details], '$[0].BusinessEntityID') = '01'
SELECT * FROM OPENJSON(@json)

The result of this query is a key-value pair of all JSON array objects in addition to the value type:

该查询的结果是除值类型以外的所有JSON数组对象的键值对:

The following JSON value types are supported:

支持以下JSON值类型:

Type code

Type description

0

null

1

string

2

int

3

true/false

4

array

5

object

类型代码

类型说明

0

空值

1个

2

整型

3

真假

4

数组

5

目的

If we know the JSON text schema, we can use OPENJSON() function to convert JSON into tabular data. We need to define the schema explicitly after this SQL Server JSON function. As an example:

如果我们知道JSON文本模式,则可以使用OPENJSON()函数将JSON转换为表格数据。 我们需要在此SQL Server JSON函数之后显式定义架构。 举个例子:

DECLARE @json nvarchar(max)SELECT @json = [Details] from [AdventureWorks2017].[Person].[Person] WHERE JSON_VALUE([Details], '$[0].BusinessEntityID') = '01'SELECT * FROM OPENJSON(@json) WITH ([BusinessEntityID] [int] ,[PersonType] [nchar](2) ,[NameStyle] [dbo].[NameStyle] ,[Title] [nvarchar](8) ,[FirstName] [dbo].[Name]  ,[MiddleName] [dbo].[Name] ,[LastName] [dbo].[Name]  ,[Suffix] [nvarchar](10) ,[EmailPromotion] [int]  ,[AdditionalContactInfo] [xml](CONTENT [Person].[AdditionalContactInfoSchemaCollection]) ,[Demographics] [xml](CONTENT [Person].[IndividualSurveySchemaCollection]) ,[rowguid] [uniqueidentifier]    ,[ModifiedDate] [datetime]  )

As shown in the image below, the query result is in tabular form.

如下图所示,查询结果采用表格形式。

索引JSON列 (Indexing JSON column )

If we need to filter our queries based on a property value within the JSON column, and we need that this property is indexed, we should add a computed column based on this value. Then we must create an index for this column. As an example:

如果需要基于JSON列中的属性值过滤查询,并且需要对该属性进行索引,则应基于此值添加计算列。 然后,我们必须为此列创建索引。 举个例子:

ALTER TABLE Person.Person
ADD vBusinessEntityID AS JSON_VALUE(Details,'$[0].BusinessEntityID')CREATE INDEX idx_BusinessEntityID
ON Person.Person(vBusinessEntityID)

将JSON数据导入SQL数据库 (Import JSON data into SQL database)

There are many methods to import JSON data into SQL database:

有很多方法可以将JSON数据导入SQL数据库:

  • Using Integration Services 使用集成服务
  • Using OPENROWSET() with OPENJSON() function 将OPENROWSET()与OPENJSON()函数一起使用

These methods are described in detail in this article, Import JSON data into SQL Server.

本文“将JSON数据导入SQL Server”中详细描述了这些方法。

结论 (Conclusion)

In this article, we have illustrated the SQL Server JSON functions added with the 2016 version. We provided some examples using the AdventureWorks database. We explained how to index properties stored within the JSON column, and finally, we briefly noted the available methods to import JSON into the SQL database.

在本文中,我们已说明了2016版本中添加SQL Server JSON函数。 我们提供了一些使用AdventureWorks数据库的示例。 我们解释了如何索引存储在JSON列中的属性,最后,我们简要地指出了将JSON导入SQL数据库的可用方法。

翻译自: https://www.sqlshack.com/sql-server-json-functions-a-bridge-between-nosql-and-relational-worlds/

sql与nosql

sql与nosql_SQL Server JSON函数:NoSQL与关系世界之间的桥梁相关推荐

  1. SQL Server JSON:性能手册

    目录 介绍 1. 数据类型 2. 存储 3. 压缩/解压 4. 压缩 5. 列存储 6. 创建JSON 7.检查JSON 8. JSONValue 9. OpenJson 10. 字符串拆分 11.  ...

  2. sql与nosql_SQL与NoSQL:差异

    sql与nosql Trending posts on SitePoint today: 今天在SitePoint上的热门帖子: 7 Ways to Make WordPress Simpler fo ...

  3. SQL Server用户自定义函数

    用户自定义函数不能用于执行一系列改变数据库状态的操作,但它可以像系统 函 数一样在查询或存储过程等的程序段中使用,也可以像存储过程一样通过 EXECUTE 命令来执行.在 SQL Server 中根据 ...

  4. PostgreSQL 10.1 手册_部分 II. SQL 语言_第 9 章 函数和操作符_9.15. JSON 函数和操作符...

    9.15. JSON 函数和操作符 表 9.43展示了可以用于两种 JSON 数据类型(见第 8.14 节)的操作符. 表 9.43. json和jsonb 操作符 操作符 右操作数类型 描述 例子 ...

  5. 妙用SQL Server聚合函数和子查询迭代求和

    本文为原创,如需转载,请注明作者和出处,谢谢! 先看看下面的表和其中的数据: t_product 图1 该表有两个字段:xh和price, 其中xh是主索引字段,现在要得到如下的查询结果: 图2 从上 ...

  6. SQL Server CONVERT() 函数,Date 函数

    From: http://www.w3school.com.cn/sql/func_convert.asp 定义和用法 CONVERT() 函数是把日期转换为新数据类型的通用函数. CONVERT() ...

  7. SQL Server日期函数集合

    SQL Server日期函数集合--1:获取系统日期和时间值函数 --getdate() SELECT GETDATE() AS 'today' --getutcdate() SELECT GETUT ...

  8. sql server 自定义函数的使用

    sql server 自定义函数的使用 自定义函数 用户定义自定义函数像内置函数一样返回标量值,也可以将结果集用表格变量返回 用户自定义函数的类型: 标量函数:返回一个标量值 表格值函数{内联表格值函 ...

  9. sql server charindex函数和patindex函数详解(转)

    charindex和patindex函数常常用来在一段字符中搜索字符或字符串.假如被搜索的字符中包含有要搜索的字符,那么这两个函数返回一个非零的整数,这个整数是要搜索的字符在被搜索的字符中的开始位数. ...

最新文章

  1. Sql Server 2005的1433端口打开和进行远程连接
  2. 【37.50%】【codeforces 745B】Hongcow Solves A Puzzle
  3. (经典)Hibernate的一对多关系映射(三)
  4. 计算机英语女人英语怎么说,英语时差:计算机和女人
  5. java jcombobox 获取值_从java中的JComboBox获取字符串值
  6. 重复包含定义 导致未定义类型不识别错误
  7. 输入一批整数,输出最大最小值,输入0结束
  8. Spark:聚类算法之LDA主题模型算法
  9. NSString 与 Unicode
  10. 【SuperResolution】Spatial resolution的含义
  11. .webp是什么文件?怎么打开这种文件
  12. ept技术_EPT和VPID简介 - osc_3xz91vxi的个人空间 - OSCHINA - 中文开源技术交流社区
  13. 个人认为程序员在工作中应该养成的一些良好习惯
  14. UE4 通过按键切换不同的HUD
  15. matlab并行加路径,matlab parfor_matlab 添加到路径_matlab 分布式计算
  16. 用C#去读取陀螺仪姿态角度传感器JY61的串口数据
  17. 接口测试平台代码实现86: 全局请求头-1
  18. 工作八年然是个二流的程序员
  19. 关于视频播放的一些总结
  20. 行空板-一款DFRobot自主研发的Python教学神器

热门文章

  1. python程序语法元素的描述_Python入门——Python程序语法元素
  2. jQuery - 获取内容和属性
  3. python模块之logging
  4. 使用GridFS上传下载图片以及其他文件
  5. C++---动态内存管理
  6. 比较默认对象和默认约束的异同_UE4对象类类型引用和类默认对象(Class Default Object,简称CDO)...
  7. 写笔记插件_Java程序员笔记(知识)管理的一点经验
  8. 这种简历咋找工作?(运营)
  9. 一加10 Pro的性能配置还是非常不错的
  10. 我想开一家美团外卖店,不做堂食,有什么好的建议吗?