当前位置: 移动技术网 > IT编程>数据库>MSSQL > sql server2016里面的json功能浅析

sql server2016里面的json功能浅析

2017年12月08日  | 移动技术网IT编程  | 我要评论

网王同人 迟到的爱,126期,宿州采购

测试一下基本的,从查询结果里面构造一个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 t1
select * from t1 for json auto
--查询结果
id     name                        chinese   math
----------- -------------------------------------------------- ----------- -----------
1      张三                         90     80
2      李四                         75     90
3      王五                         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 值

好,本次实验到此为止~然后我试下解析json 的语法之类的再分享~

感想就是其实语法应该跟xml类型的相差无几~但是数据库之前支持了xml 数据类型,然后json却只能通过字符串去转换解析。

以上所述是小编给大家介绍的sql server2016里面的json功能,希望对大家有所帮助

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网