sql server2016里面的json功能怎么使用

47次阅读
没有评论

共计 2118 个字符,预计需要花费 6 分钟才能阅读完成。

这篇文章主要介绍“sql server2016 里面的 json 功能怎么使用”,在日常操作中,相信很多人在 sql server2016 里面的 json 功能怎么使用问题上存在疑惑,丸趣 TV 小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”sql server2016 里面的 json 功能怎么使用”的疑惑有所帮助!接下来,请跟着丸趣 TV 小编一起来学习吧!

测试一下基本的,从查询结果里面构造一个 json 的格式

create table t1(ID int identity,name nvarchar(50),Chinese int ,Math int)insert into t1 values (张三 ,90,80),(李四 ,75,90),(王五 ,68,100)select * from t1select * from t1 for json auto-- 查询结果 ID name Chinese Math----------- -------------------------------------------------- ----------- -----------1  张三  90 802  李四  75 903  王五  68 100--json  格式 [{ID :1, name : 张三 , Chinese :90, Math :80},{ID :2, name : 李四 , Chinese :75, Math :90},{ID :3, name : 王五 , Chinese :68, Math :100}]

这个是默认模式下面使用 json 的查询结果。是不是十分清晰

然后我们再接再厉,第二波是这样纸的。假如我们要继续搞有层级关系的。我们还可以这样写。比方说把成绩放在一个叫 points 的节点里面,也是可以分层的

select ID, name, Chinese as [Points.Chinese], Math as [Points.Math] from t1 for json path-- 结果 json[{ID :1, name : 张三 , Points :{ Chinese :90, Math :80}},{ID :2, name : 李四 , Points :{ Chinese :75, Math :90}},{ID :3, name : 王五 , Points :{ Chinese :68, Math :100}}]

他们的分数就放在了 json 里面的, 被一个 point 包住了。

如果说我要在这个结果里面添加一个头来包住,当然,我可以使用每个列来个别名 [root.col] 来实现,然而就有点啰嗦了。所以我们可以使用这个 root 的关键字来添加一个顶节点

select ID, name, Chinese as [Points.Chinese], Math as [Points.Math] from t1 for json path,root(root) -- 返回的 json 结果 {root :[ { ID :1, name : 张三 , Points :{ Chinese :90, Math :80}}, {ID :2, name : 李四 , Points :{ Chinese :75, Math :90}},{ID :3, name : 王五 , Points :{ Chinese :68, Math :100}}]}

当然咯,查询嘛,录入数据总是难免遇到 null 值,在这方面,for json 是如何处理的呢?我在测试表添加一条数据在来查询

insert into t1 values (赵六 ,100,null)select ID, name, Chinese as [Points.Chinese], Math as [Points.Math] from t1 where id in(3, 4) for json auto--json 的返回结果 [{ID :3, name : 王五 , Points.Chinese :68, Points.Math :100},{ID :4, name : 赵六 , Points.Chinese :100}]

auto 模式下,如果是空值,将会忽略该属性。这样的话很容易就每一个集合返回的属性数量都不一来,这样不好看。所以应对这种情况,我们可以使用 incluede_null_values 关键字,即使是空值,也带出来

select ID, name, Chinese as [Points.Chinese], Math as [Points.Math] from t1 where id in(3, 4) for json auto, include_null_values--json  的返回结果 [{ID :3, name : 王五 , Points.Chinese :68, Points.Math :100},{ID :4, name : 赵六 , Points.Chinese :100, Points.Math :null}]

使用了这个关键字,就可以把空值带出来,里面的值是 Null 值

到此,关于“sql server2016 里面的 json 功能怎么使用”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注丸趣 TV 网站,丸趣 TV 小编会继续努力为大家带来更多实用的文章!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-07-18发表,共计2118字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)