在sqlserver 中存储json ,需要用字符串类型进行存储,一般用nvarchar()或 varchar()进行存储,不要用text进行存储,用text时候,json的函数不支持。
主要介绍5个函数:
(1)openJson:打开Json字符串
(2)IsJson:判断一个字符串是不是合法的Json格式。是返回1,否返回0,null返回null。
(3)Json_Value:从Json字符串中提取值。
(4)Json_Query:Json字符串中提取对象或数组。
(5)Json_Modify:更新Json字符串中的属性值,并返回更新的Json字符串。
新建wm_json_demo 表:
CREATE TABLE demo_plus.dbo.wm_json_demo (
id int IDENTITY(1,1) NOT NULL,
json_detail varchar(max) NOT NULL,
CONSTRAINT PK_wm_json_demo PRIMARY KEY (id)
);
下面以wm_json_demo 为例,演示以上5个json操作相关的函数
INSERT INTO demo_plus.dbo.wm_json_demo (json_detail) VALUES('{"key":3,"value1":10,"value2":[{"vv21":13,"vv22":103}],"value3":null}');
INSERT INTO demo_plus.dbo.wm_json_demo (json_detail) VALUES('{"key":4,"value1":15,"value2":[{"vv21":13,"vv22":103}],"value3":"10"}');
INSERT INTO demo_plus.dbo.wm_json_demo (json_detail) VALUES('{"key":7,"value1":20,"value2":[{"vv21":13,"vv22":103}],"value3":"15"}');
SELECT
IsJson(json_detail) as IsJson
from
demo_plus.dbo.wm_json_demo
用法:Json_Value (cloumn_name,’$.json_field_name’) from table
用法:Json_Query (cloumn_name,’$.json_field_name’) from table
SELECT
JSON_VALUE(json_detail,'$.key') as 'key',
JSON_VALUE(json_detail,'$.value1') as value1,
JSON_value(json_detail,'$.value2') as value2,
JSON_QUERY(json_detail,'$.value2') as value2_query,
JSON_VALUE(json_detail,'$.value3') as value3
from demo_plus.dbo.wm_json_demo;
JSON_MODIFY(column_name, ‘$.json_field’, ‘change_info’);
SELECT
JSON_MODIFY(json_detail,
'$.value1',
11) as json_detail
from
demo_plus.dbo.wm_json_demo
where
JSON_VALUE(json_detail,
'$.key')= 7;
这里附上官网地址,有兴趣的小伙伴可以去看看:
https://docs.microsoft.com/en-us/sql/relational-databases/json/json-data-sql-server?view=sql-server-ver15