SQL Server 2016 的JSON功能
測(cè)試一下基本的,從查詢結(jié)果里面構(gòu)造一個(gè)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 --查詢結(jié)果 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}]
?這個(gè)是默認(rèn)模式下面使用json的查詢結(jié)果。是不是十分清晰
然后我們?cè)俳釉賲?,第二波是這樣紙的。假如我們要繼續(xù)搞有層級(jí)關(guān)系的。我們還可以這樣寫。比方說把成績放在一個(gè)叫points 的節(jié)點(diǎn)里面, 也是可以分層的
select?ID, ????????name, ????????Chinese?as?[Points.Chinese], ????????Math?as?[Points.Math] ????from?t1?for?json?path --結(jié)果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}} ]
他們的分?jǐn)?shù)就放在了json 里面的,被一個(gè)point 包住了。
如果說我要在這個(gè)結(jié)果里面添加一個(gè)頭來包住,當(dāng)然,我可以使用每個(gè)列來個(gè)別名 [root.col] 來實(shí)現(xiàn),然而就有點(diǎn)啰嗦了。所以我們可以使用這個(gè)root 的關(guān)鍵字來添加一個(gè)頂節(jié)點(diǎn)
select?ID, ????????name, ????????Chinese?as?[Points.Chinese], ????????Math?as?[Points.Math] ????from?t1?for?json?path,root('root')? --返回的json結(jié)果 {"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}}]}
當(dāng)然咯,查詢嘛,錄入數(shù)據(jù)總是難免遇到null值,在這方面,for json 是如何處理的呢? 我在測(cè)試表添加一條數(shù)據(jù)在來查詢
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的返回結(jié)果 [{"ID":3,"name":"王五","Points.Chinese":68,"Points.Math":100},{"ID":4,"name":"趙六","Points.Chinese":100}]
auto 模式下,如果是空值,將會(huì)忽略該屬性。這樣的話很容易就每一個(gè)集合返回的屬性數(shù)量都不一來,這樣不好看。所以應(yīng)對(duì)這種情況,我們可以使用 incluede_null_values 關(guān)鍵字,即使是空值,也帶出來?
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?的返回結(jié)果 [{"ID":3,"name":"王五","Points.Chinese":68,"Points.Math":100},{"ID":4,"name":"趙六","Points.Chinese":100,"Points.Math":null}]
使用了這個(gè)關(guān)鍵字,就可以把空值帶出來,里面的值是Null 值
?
好,本次實(shí)驗(yàn)到此為止~然后我試下解析json 的語法之類的再分享~
感想就是其實(shí)語法應(yīng)該跟xml類型的相差無幾~但是數(shù)據(jù)庫之前支持了xml 數(shù)據(jù)類型,然后json卻只能通過字符串去轉(zhuǎn)換解析。