数据库sql创建标量值函数
In this article, we will explore JSON_VALUE() function in SQL Server to extract scalar values from JSON data.
在本文中,我们将探索SQL Server中的JSON_VALUE()函数,以从JSON数据中提取标量值。
JSON简介 (Introduction to JSON)
JSON is an acronym for “JavaScript Object Notation”. It is a lightweight data exchange language. If you are familiar with XML, it is a bit hard to understand. You can easily interpret JSON formatted data using its key-value pair.
JSON是“ JavaScript对象表示法”的缩写。 它是一种轻量级的数据交换语言。 如果您熟悉XML,将很难理解。 您可以使用其键值对轻松解释JSON格式的数据。
JSON is a popular language and many NoSQL databases such a Couchbase, AWS DynamoDB. It is popular in modern web and mobile applications.
JSON是一种流行的语言,它是许多NoSQL数据库,例如Couchbase,AWS DynamoDB。 它在现代Web和移动应用程序中很流行。
SQL Server 2016 and later supports JSON format data. You should know JSON format and work with JSON data in SQL Server. It also creates a bridge between a relational database and NoSQL systems.
SQL Server 2016及更高版本支持JSON格式数据。 您应该了解JSON格式,并在SQL Server中使用JSON数据。 它还在关系数据库和NoSQL系统之间建立了桥梁。
SQL Server provides various built-in-functions to parse, read, transform, and convert JSON objects. You can also format the T-SQL results in the JSON format. You can go through article category k in SQLShack to understand more details about it.
SQL Server提供了各种内置函数来解析,读取,转换和转换JSON对象。 您也可以使用JSON格式格式化T-SQL结果。 您可以在SQLShack中浏览文章类别k,以了解有关它的更多详细信息。
You can refer to the following image from Microsoft docs to understand the interoperability between SQL table and JSON.
您可以参考Microsoft文档中的以下图像,以了解SQL表和JSON之间的互操作性。
We have the following JSON functions in SQL Server:
我们在SQL Server中具有以下JSON函数:
- ISJSON(): It checks whether we have a valid JSON or not ISJSON():它检查我们是否具有有效的JSON
- JSON_VALUE(): We can extract a scalar value from the JSON string. We will explore this function in detail in this article JSON_VALUE():我们可以从JSON字符串中提取标量值。 我们将在本文中详细探讨此功能
- JSON_QUERY: We can extract an array or string from the JSON_QUERY() output JSON_QUERY:我们可以从JSON_QUERY()输出中提取数组或字符串
- JSON_MODIFY(): We can modify a value in the JSON Data using this JSON-MODIFY() function JSON_MODIFY():我们可以使用此JSON-MODIFY()函数修改JSON数据中的值
JSON_VALUE()的语法 (Syntax of JSON_VALUE())
JSON_VALUE ( expression ,[Path Mode] JSON_path )
JSON_VALUE(表达式,[路径模式] JSON_path)
- Expression: It is a variable or column containing a JSON string. It should be a valid expression, and else it returns an error 表达式 :它是包含JSON字符串的变量或列。 它应该是一个有效的表达式,否则返回错误
- JSON_Path: It is the location of a scalar value in the JSON string JSON_Path:这是JSON字符串中标量值的位置
- Path mode: It is an optional argument. We can specify the 路径模式:这是一个可选参数。 我们可以在这种模式下指定lax or 宽松或strict value in this mode. It uses LAX as a default path mode. We will understand it using examples 严格的值。 它使用LAX作为默认路径模式。 我们将通过示例了解它
Let’s understand the JSON_VALUE() function using various examples.
让我们使用各种示例来了解JSON_VALUE()函数。
示例1:从JSON字符串中搜索键值 (Example 1: Search a key value from JSON string)
In the query below, we defined a JSON expression and path.
在下面的查询中,我们定义了JSON表达式和路径。
- It has a JSON expression defined as a key (Name) and its value (“Rajendra”) 它具有定义为键(名称)及其值(“ Rajendra”)的JSON表达式
It specifies $.Name argument as JSON path. This path should reference the key in the JSON expression
它指定$ .Name参数作为JSON路径。 此路径应引用JSON表达式中的键
SELECT JSON_VALUE('{"Name": "Rajendra"}', '$.Name') AS 'Output';
We cannot use a space character in the JSON key. For example, if we run the following code for a key (First Name) and want to retrieve a value for it, it gives us inappropriate format error.
我们不能在JSON键中使用空格字符。 例如,如果我们为密钥(名字)运行以下代码,并想为其获取值,则会给我们带来不适当的格式错误。
SELECT JSON_VALUE('{"First Name": "Rajendra"}', '$.First Name') AS 'Output';
In the below query, the JSON path does not contain an argument value that does not refer to the JSON string. Here, the JSON string does not have the first name key, therefore so we get NULL value in the output using default path mode.
在下面的查询中,JSON路径不包含不引用JSON字符串的参数值。 此处,JSON字符串没有名字密钥,因此,我们使用默认路径模式在输出中获得NULL值。
SELECT JSON_VALUE('{"Name": "Rajendra"}', '$.FirstName') AS 'Output';
示例2:JSON数据中的默认LAX路径模式 (Example 2: Default LAX path mode in JSON Data)
As we specified earlier, JSON_VALUE() function uses LAX as the default mode. We can specify it explicitly as well, and it returns a similar output as shown below.
正如我们之前指定的,JSON_VALUE()函数使用LAX作为默认模式。 我们也可以显式指定它,并且它返回类似如下所示的输出。
示例3:JSON中的严格路径模式 (Example 3: Strict path mode in JSON)
Let’s change the mode to Strict, and it gives you an error message in case the key does not exist.
让我们将模式更改为“严格”,如果密钥不存在,它会给您一条错误消息。
SELECT JSON_VALUE('{"Name": "Rajendra"}', 'strict$.FirstName') AS 'Output';
Now, let’s change the correct key from the JSON string, and we get output in the Strict path.
现在,让我们从JSON字符串中更改正确的密钥,然后在Strict路径中获得输出。
You should take a note that it is a case sensitive operation; if we specify the path mode to Strict, it gives the following error.
您应该注意这是区分大小写的操作; 如果我们将路径模式指定为S trict,则会出现以下错误。
Similarly, you get an error if you use a capital letter in LAX mode, it also gives the error message.
同样,如果在LAX模式下使用大写字母,则会出现错误,并且还会显示错误消息。
示例4:通过JSON_VALUE()函数在JSON数据中使用数组 (Example 4: Use an Array in JSON data with JSON_VALUE() function)
We can use an array to store multiple values. It uses square brackets ([]) to define the array. In the below code, we have an array for Employees records and puts JSON into a variable called @data.
我们可以使用数组来存储多个值。 它使用方括号([])定义数组。 在下面的代码中,我们有一个Employees记录数组,并将JSON放入名为@data的变量中。
The first record in JSON is always index as zero. For example, in the array, we get the first record by specifying index position zero.
JSON中的第一条记录始终是零索引。 例如,在数组中,我们通过指定索引位置零获得第一条记录。
DECLARE @data NVARCHAR(4000);
SET @data = N'{
"Employees": [
{
"EmpName": "Rohan Sharma",
"Department": "IT",
"Address": "101, Sector 5, Gurugram, India",
"Salary": 100000
},
{
"EmpName": "Manohar Lal",
"Department": "Human Resources",
"Address": "17, Park Avenue, Mumbai, India",
"Salary": 78000
}
]
}';
SELECT JSON_VALUE(@data, '$.Employees[0].EmpName') AS 'Name',
JSON_VALUE(@data, '$.Employees[0].Department') AS 'Department',
JSON_VALUE(@data, '$.Employees[0].Address') AS 'Address',
JSON_VALUE(@data, '$.Employees[0].Salary') AS 'Salary';
It returns the output of the first employee data.
它返回第一个员工数据的输出。
We can use SQL UNION ALL operator to retrieve both records and display them in a tabular format.
我们可以使用SQL UNION ALL运算符检索两个记录并以表格格式显示它们。
DECLARE @data NVARCHAR(4000);
SET @data = N'{
"Employees": [
{
"EmpName": "Rohan Sharma",
"Department": "IT",
"Address": "101, Sector 5, Gurugram, India",
"Salary": 100000
},
{
"EmpName": "Manohar Lal",
"Department": "Human Resources",
"Address": "17, Park Avenue, Mumbai, India",
"Salary": 78000
}
]
}';
SELECT JSON_VALUE(@data, '$.Employees[0].EmpName') AS 'Name',
JSON_VALUE(@data, '$.Employees[0].Department') AS 'Department',
JSON_VALUE(@data, '$.Employees[0].Address') AS 'Address',
JSON_VALUE(@data, '$.Employees[0].Salary') AS 'Salary'
UNION ALL
SELECT JSON_VALUE(@data, '$.Employees[1].EmpName') AS 'Name',
JSON_VALUE(@data, '$.Employees[1].Department') AS 'Department',
JSON_VALUE(@data, '$.Employees[1].Address') AS 'Address',
JSON_VALUE(@data, '$.Employees[1].Salary') AS 'Salary'
We get the following output from the JSON_VALUE() function in an array.
我们从数组中的JSON_VALUE()函数获得以下输出。
Similarly, look at the following example. It holds an array for favorite subjects of a student in the info JSON key. We require to retrieve student name and his second favorite subject listed in an array.
同样,请看以下示例。 它在info JSON键中包含一个学生喜欢的学科的数组。 我们需要检索一个数组中列出的学生姓名和他的第二个最喜欢的科目。
We can use the following code with the JSON_Value function.
我们可以将以下代码与JSON_Value函数一起使用。
Retrieve the student name using the JSON_VALUE function, as shown below. We specify the JSON key (info) and specify the item name you need the data
如下所示,使用JSON_VALUE函数检索学生姓名。 我们指定JSON键(信息)并指定您需要数据的商品名称
SELECT JSON_VALUE(@data, '$.info.Name') AS 'Name',
For the second favorite subject, we specify the array element position. As you know, in an array first item starts with zero index and we use [1] for the second element
对于第二个喜欢的主题,我们指定数组元素的位置。 如您所知,在数组中,第一项以零索引开头,第二个元素使用[1]
JSON_VALUE(@data, '$.info.Favorite_Subject[1]') AS 'Favorite Subject'; DECLARE @data NVARCHAR(MAX); SET @data = N'{ "info":{ "ID":1, "Name":"Akshat", "address":{ "City":"Gurgaon", "Country":"India" }, "Favorite_Subject":["English", "Science"] }, "type":"student" }'; SELECT JSON_VALUE(@data, '$.info.Name') AS 'Name', JSON_VALUE(@data, '$.info.Favorite_Subject[1]') AS 'Favorite Subject';
It gives you the desired output, as shown below.
它将为您提供所需的输出,如下所示。
As specified earlier, we can get a scalar value from JSON data using the JSON_VALUE() function. In the above example, if we try to retrieve a complete array, it returns a NULL value in the output using the default lax path mode.
如前所述,我们可以使用JSON_VALUE()函数从JSON数据中获取标量值。 在上面的示例中,如果我们尝试检索一个完整的数组,它将使用默认的lax路径模式在输出中返回NULL值。
DECLARE @data NVARCHAR(MAX);
SET @data = N'{
"info":{
"ID":1,
"Name":"Akshat",
"address":{
"City":"Gurgaon",
"Country":"India"
},
"Favorite_Subject":["English", "Science"]
},
"type":"student"
}';
SELECT JSON_VALUE(@data, '$.info.Name') AS 'Name',
JSON_VALUE(@data, '$.info.Favorite_Subject') AS 'Favorite Subject';
We do not want NULL value in the output. It gives an assumption that the specified key does not exist in JSON expression. We should use a strict path mode to get the exact error message.
我们不希望在输出中使用NULL值。 假设指定的键在JSON表达式中不存在。 我们应该使用严格的路径模式来获取确切的错误消息。
DECLARE @data NVARCHAR(MAX);
SET @data = N'{
"info":{
"ID":1,
"Name":"Akshat",
"address":{
"City":"Gurgaon",
"Country":"India"
},
"Favorite_Subject":["English", "Science"]
},
"type":"student"
}';
SELECT JSON_VALUE(@data, '$.info.Name') AS 'Name',
JSON_VALUE(@data, 'strict$.info.Favorite_Subject') AS 'Favorite Subject';
You get an error in the strict mode because it could not retrieve the array from the JSON data.
在严格模式下会出现错误,因为它无法从JSON数据中检索数组。
示例5:从嵌套的JSON密钥数据检索值 (Example 5: Retrieve value from a nested JSON key data)
In the below code, we have an address key that contains further nested elements. For example, address contains values for different keys FlatNo, Locality, and City.
在下面的代码中,我们有一个包含其他嵌套元素的地址键。 例如,地址包含不同键FlatNo,Locality和City的值。
Now, we want to retrieve a specific subkey from the Address JSON key. For example, we require City from the Address key. For this requirement, we need to specify the key order in the following format.
现在,我们想从Address JSON键中检索特定的子键。 例如,我们需要从地址键中输入城市。 为此,我们需要以以下格式指定键顺序。
JSON_VALUE(@data, '$.Employees[0].Address.City')
- $.Employee[0] refers to the first record in the array $ .Employee [0]引用数组中的第一条记录
The address is the first key in Employees, and City is the second key, so the complete expression is Employees[0].Address.City
地址是员工中的第一个键,城市是第二个键,因此完整的表达式是员工[0] .Address.City
DECLARE @data NVARCHAR(4000); SET @data = N'{ "Employees": [ { "EmpName": "Rohan Sharma", "Department": "IT", "Address": {"FlatNo":101,"Locality":"Sector 5", "City":"Gurugram", "Country:"India", "Salary": 100000 }, ] }'; SELECT JSON_VALUE(@data, '$.Employees[0].EmpName') AS 'Name', JSON_VALUE(@data, '$.Employees[0].Address.City') AS 'City';
It fetches the information from the JSON data and gives you an appropriate output.
它从JSON数据中获取信息,并为您提供适当的输出。
结论 (Conclusion)
In this article, we explored the useful JSON_VALUE() function to retrieve a scalar value from the JSON data using various examples. It also demonstrated the difference in lax and strict path modes available with this function. You should explore JSON and process it to handle it with SQL Server.
在本文中,我们使用各种示例探索了有用的JSON_VALUE()函数以从JSON数据中检索标量值。 它还展示了此功能可用的宽松路径模式和严格路径模式的差异。 您应该浏览JSON并对其进行处理以使用SQL Server进行处理。
翻译自: https://www.sqlshack.com/extract-scalar-values-from-json-data-using-json_value/
数据库sql创建标量值函数