測試一下基本的,從查詢結果裏面構造一個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的查詢結果。是否是十分清晰json
而後咱們再接再礪,第二波是這樣紙的。假如咱們要繼續搞有層級關係的。咱們還能夠這樣寫。比方說把成績放在一個叫points 的節點裏面, 也是能夠分層的ide
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 的關鍵字來添加一個頂節點spa
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 是如何處理的呢? 我在測試表添加一條數據在來查詢code
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 關鍵字,即便是空值,也帶出來xml
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 值blog
好,本次實驗到此爲止~而後我試下解析json 的語法之類的再分享~字符串
感想就是其實語法應該跟xml類型的相差無幾~可是數據庫以前支持了xml 數據類型,而後json卻只能經過字符串去轉換解析。這個後面我再實驗一下it