SQL Server JSON 格式資料查詢、修改

在 SQL Server 中可以這樣查詢:
    
select '123' AS resut;

+-----+
|resut|
+-----+
|{}   |
+-----+
    

接下來都會使用這個方式做示範。

判斷是否為 JSON 格式

使用 ISJSON 來判斷是否為 JSON 格式,是則回傳 1 ,不是則回傳 0
    
select ISJSON('{}') AS resut1, ISJSON('123') AS result2

+------+-------+
|resut1|result2|
+------+-------+
|1     |0      |
+------+-------+
    

讀取 JSON 指定物件名稱資料

使用 JSON_VALUE 取得,參數一是欄位名稱,參數二是 JSON 路徑表示式 (JSON Path Expression)
    
select JSON_VALUE('{"Key1":"Value"}', '$.Key1') AS resut1
     , JSON_VALUE('{"Key1":"Value"}', '$.Key2') AS result2
     , JSON_VALUE('{"Key1": {"Key2": "Value2"} }', '$.Key1.Key2') AS result3

+------+-------+-------+
|resut1|result2|result3|
+------+-------+-------+
|Value |null   |Value2 |
+------+-------+-------+
    

更新 JSON 指定物件資料

假設有一個資料表叫做 users , attributes 欄位是 json,他的內容如下:
    
{
  "Key1": "Value1",
  "Key2": "Value2"
}
    

要更新 Value1 為 NewValue 可以這樣做
    
update users set attributes = JSON_MODIFY(attributes, '$.Key1', N'NewValue' ) where id = 1;
    



參考資料:
Microsoft.Learn - ISJSON (Transact-SQL)
Microsoft.Learn - JSON_VALUE (Transact-SQL)
Microsoft.Learn - JSON_MODIFY (Transact-SQL)

留言

張貼留言

如果有任何問題、建議、想說的話或文章題目推薦,都歡迎留言或來信: a@ruyut.com