Chapter29 Examples
Chapter29 Examples
{ "info": {
"who": "Fred" ,"where": "Microsoft"
,"friends": [{ "name": "Lili", "rank": 5}
,{"name": "Hank", "rank": 7}]} }
Example 29.2
USE sample;
CREATE TABLE json_table
(id INT PRIMARY KEY IDENTITY, person_and_friends NVARCHAR(2000));
-- Insert a couple of rows
INSERT INTO json_table (person_and_friends) VALUES
(N' {"info":
{"who": "Fred" ,"where": "SQL Server" ,
"friends": [{ "name": "Lili", "rank": 5} ,{"name": "Hank", "rank": 7}]}}');
INSERT INTO json_table (person_and_friends) VALUES
(N' {"info":{"who": "Tom", "where": "IBM", "friends": [ { "name": "Sharon", "rank": 2},
{"name": "Monty", "rank": 3} ] }}');
INSERT INTO json_table (person_and_friends) VALUES
(N' {"info":{ "who": "Jack", "friends": [ { "name": "Connie" } ] }}');
INSERT INTO json_table (person_and_friends) VALUES
(N' {"info":{ "who": "Joe", "friends": [ { "name": "Doris" }, {"rank": 1} ] }}')
INSERT INTO json_table (person_and_friends) VALUES
(N' {"info": {"who":"Mabel","where":"PostgresSQL","friends":[{"name":"Buck","rank":
6}]}}');
INSERT INTO json_table (person_and_friends) VALUES
(N' {"info":{"who": "Louise", "where": "Hanna" }}');
Example 29.3
USE sample;
SELECT dept_no, dept_name
FROM department FOR JSON AUTO;
Example 29.5
USE sample;
SELECT dept_no AS [Department.Number], dept_name AS [Department.Name]
FROM department
FOR JSON PATH, ROOT ('Departments');
Example 29.6
USE sample;
SELECT id, person_and_friends
FROM json_table
WHERE ISJSON(person_and_friends) > 0;
Example 29.7
USE sample;
SELECT Id, JSON_VALUE(person_and_friends, '$.info.where') AS project
FROM json_table
WHERE ISJSON(person_and_friends) > 0
AND JSON_VALUE(person_and_friends, '$.info.who') = 'Fred';
Example 29.8
USE sample;
SELECT id, person_and_friends,
JSON_QUERY(person_and_friends, '$.info.where')
FROM json_table;
Example 29.9
UPDATE json_update_table
SET person_and_friends= json_modify(person_and_friends,
'append $.info.friends', 'Wendy')
WHERE id = 1;
Example 29.12
UPDATE json_update_table
SET person_and_friends = json_modify(person_and_friends,
'$.info.surname', NULL)
WHERE id = 1;
Example 29.14
UPDATE json_update_table
SET person_and_friends = json_modify(person_and_friends,
'$.info.friends', NULL)
WHERE id = 1;
UPDATE json_update_table
SET person_and_friends = json_modify (person_and_friends,
'$.info.friends', 'Lili, Wendy,Hank')
WHERE id = 1;