首页 > 数据库 >SQL Server 操作JSON数据库列

SQL Server 操作JSON数据库列

时间:2023-09-01 14:11:06浏览次数:37  
标签:-- doc VALUE Server content JSON SQL givenName

use [tempdb]

declare @JSON nvarchar(max)
set @JSON=N'{
  "id": "WakefieldFamily",
  "parents": [
      { "familyName": "Wakefield", "givenName": "Robin" },
      { "familyName": "Miller", "givenName": "Ben" }
  ],
  "children": [
    {
      "familyName": "Merriam",
      "givenName": "Jesse",
      "gender": "female",
      "grade": 1,
      "pets": [
          { "givenName": "Goofy" },
          { "givenName": "Shadow" }
      ]
    },
    { 
        "familyName": "Miller",
        "givenName": "Lisa",
        "gender": "female",
        "grade": 8
    }
  ],
  "address": { "state": "NY", "county": "Manhattan", "city": "NY" },
  "creationDate": 1431620462,
  "isRegistered": false
}'
--此 JSON 文档包含嵌套的复杂元素,存储在下面的示例表中:
--CREATE TABLE Families (
--   id int identity constraint PK_JSON_ID primary key,
--   doc nvarchar(max)
--)
--insert into Families(doc) select @JSON

SELECT * FROM Families WHERE ISJSON(doc) > 0

--使用 JSON_VALUE 函数从 JSON 文本中提取值
SELECT JSON_VALUE(f.doc, '$.id')  AS Name, 
       JSON_VALUE(f.doc, '$.address.city') AS City,
       JSON_VALUE(f.doc, '$.address.county') AS County
FROM Families f 
WHERE JSON_VALUE(f.doc, '$.id') = N'WakefieldFamily'
ORDER BY JSON_VALUE(f.doc, '$.address.city') DESC, JSON_VALUE(f.doc, '$.address.state') ASC
--WakefieldFamily    NY    Manhattan

--使用 JSON_QUERY 函数从 JSON 文本中提取对象或数组
SELECT JSON_QUERY(f.doc, '$.address') AS Address,
       JSON_QUERY(f.doc, '$.parents') AS Parents,
       JSON_QUERY(f.doc, '$.parents[0]') AS Parent0
FROM Families f 
WHERE JSON_VALUE(f.doc, '$.id') = N'WakefieldFamily'

--分析嵌套式 JSON 集合
SELECT JSON_VALUE(f.doc, '$.id')  AS Name, 
       JSON_VALUE(f.doc, '$.address.city') AS City,
       c.givenName, c.grade
FROM Families f
CROSS APPLY OPENJSON(f.doc, '$.children') WITH(grade int, givenName nvarchar(100))  c

--查询嵌套式分层 JSON 子数组
SELECT    familyName,
    c.givenName AS childGivenName,
    c.firstName AS childFirstName,
    p.givenName AS petName 
FROM Families f 
CROSS APPLY OPENJSON(f.doc) WITH (familyName nvarchar(100), children nvarchar(max) AS JSON)
CROSS APPLY OPENJSON(children) WITH (givenName nvarchar(100), firstName nvarchar(100), pets nvarchar(max) AS JSON) as c
OUTER APPLY OPENJSON (pets) WITH (givenName nvarchar(100))  as p

--JSON_VALUE 和 JSON_QUERY 之间的主要区别在于 JSON_VALUE 返回标量值,而 JSON_QUERY 返回数组或对象。

--use [AdventureWorks]

--修改 JSON 对象
DECLARE @info NVARCHAR(100)='{"name":"John","skills":["C#","SQL"]}'
PRINT @info

-- Update skills array  
SET @info=JSON_MODIFY(@info,'$.skills',JSON_QUERY('["C#","T-SQL","Azure"]'))
PRINT @info

--修改 JSON 对象
DECLARE @RespData NVARCHAR(max)=N'{"code": "000","message": "成功","data": {"secretKey": "","content": "{\"rule_result\":{\"risk_level\":\"\",\"reason_code\":[],\"hitted_rules\":[]}}"}}'
declare @content NVARCHAR(max)=JSON_VALUE(@RespData,'$.data.content')
SET @content=JSON_MODIFY(@content,'$.rule_result.hitted_rules',JSON_QUERY(N'[{"name":"ZZC_CRS0027","description":"申请人最近7天到30天在网贷机构出现过","rule_type":"跨机构比对","risk_level":"M"}]'))
SET @RespData=JSON_MODIFY(@RespData,'$.data.content',@content)
--select @content,@RespData
select JSON_VALUE(@RespData,'$.code'),JSON_VALUE(@RespData,'$.message'),JSON_VALUE(@RespData,'$.data.content'),JSON_VALUE(JSON_VALUE(@RespData,'$.data.content'),'$.rule_result.hitted_rules[0].name')


--https://learn.microsoft.com/zh-cn/sql/t-sql/functions/json-value-transact-sql?view=sql-server-ver16
--drop table [Families]

--Test

DECLARE @JSONText NVARCHAR(MAX);

SET @JSONText = '{"info": {"address": [{"town": "Belgrade"}, {"town": "Paris"}, {"town":"Madrid"}]}}';
SELECT @JSONText

SET @JSONText = JSON_MODIFY(@json, '$.info.address[1].town', 'London');
SET @JSONText = JSON_MODIFY(@json, 'append $.info.address', N'{"town":"BeiJing"}');

SELECT @JSONText

 

标签:--,doc,VALUE,Server,content,JSON,SQL,givenName
From: https://www.cnblogs.com/hofmann/p/17671725.html

相关文章

  • postgresql常用命令
    PostgreSQL是一个强大的开源关系型数据库管理系统,它提供了许多用于管理数据库和执行操作的命令。以下是一些常用的PostgreSQL命令:连接到数据库:psql-hhostname-ddbname-Uusername这个命令用于连接到指定的数据库,需要提供主机名、数据库名和用户名。你可以根据需要修......
  • MySQL InnoDB 是怎么使用 B+ 树存数据的?
    这里限定MySQLInnoDB存储引擎来进行阐述,避免不必要的阅读歧义。首先通过一篇文章简要了解下B树的相关知识:你好,我是B树。B+树是在B树基础上的变种,主要区别包括:1、所有数据都存储在叶节点,其它几点作为索引存储。2、数据节点添加链指针,便于横向检索。数据是怎么......
  • mysql字符集批量修改
    修改所有数据库字符集SELECTCONCAT('ALTERDATABASE',SCHEMA_NAME,'CHARACTERSETutf8mb4COLLATEutf8mb4_bin;')as'Fanrncho'FROMinformation_schema.`SCHEMATA`WHEREDEFAULT_CHARACTER_SET_NAMERLIKE'utf8mb4'ANDSCHEMA_NAME......
  • mysql数据库性能优化参考
    原文链接:https://blog.csdn.net/qq_34777982/article/details/125788079硬件和操作系统层面的优化硬件:cpu、内存、磁盘io、网络带宽操作系统:应用文件句柄(ulimit-aopenfiles)网络配置架构设计层面的优化集群方式(主从集群或者主主集群):避免单点故障读写分离:读写分开,将压力分担,避......
  • SQL ALTER TABLE 语句
       ......
  • SQL AND & OR 运算符
    ......
  • SQL 入门篇之什么是别名?
    SQL入门篇之什么是别名?   ......
  • SQL BETWEEN 操作符
       ......
  • mysql备份恢复
    备份某个表:mysqldump-uusername-ppassworddatabase_nametable_name>backup_file.sql备份多个表:mysqldump–uusername-ppassworddatabase_nametable1table2>BackupName.sql备份整个库:mysqldump-uusername-ppassworddatabase_name>backup_file.sql备份多......
  • newtonsoft.json
    https://www.newtonsoft.com/jsonProductproduct=newProduct();product.Name="Apple";product.Expiry=newDateTime(2008,12,28);product.Sizes=newstring[]{"Small"};stringjson=JsonConvert.SerializeObject(product);//{......