How to insert or update key: value
pair:
If you want to " ... check if that JSON property exists, if exists then just update value, if not then insert that property with predefined value ...", the remarks section from the JSON_MODIFY
documentation gives you one possible solution:
The JSON_MODIFY function lets you either update the value of an
existing property, insert a new key:value pair, or delete a key based
on a combination of modes and provided values.
If you execute JSON_MODIFY
with not NULL
value, in lax
mode, the function will try to:
- insert a new
key:value
pair if the specified path
doesn't exist.
- update the existing
key: value
pair if the specified path
exists.
Table:
CREATE TABLE #Data (
Settings nvarchar(100)
)
INSERT INTO #Data
(Settings)
VALUES
(N'{"name":"John","skills":["C#","SQL"]}')
Statement:
-- Update existing key
UPDATE #Data
SET Settings = JSON_MODIFY(Settings, 'lax $.name', 'Mike')
WHERE ISJSON(Settings) = 1
-- Insert new key
UPDATE #Data
SET Settings = JSON_MODIFY(Settings, 'lax $.day', 'Sunday')
WHERE ISJSON(Settings) = 1
Output:
SELECT *
FROM #Data
Settings
{"name":"Mike","skills":["C#","SQL"],"day":"Sunday"}
How to check for specific key
or value
:
If you want to check if specific key
exists, use OPENJSON()
:
SELECT *
FROM #Data d
CROSS APPLY OPENJSON(d.Settings) j
WHERE j.[key] = 'name'
If you want to check if specific value
exists, use JSON_VALUE()
:
SELECT *
FROM #Data
WHERE JSON_VALUE(Settings, '$.name') = 'Mike'
Example with the statement from the question:
DECLARE @info NVARCHAR(100)='{"name":"John","skills":["C#","SQL"]}'
IF (ISJSON(@info) > 0) BEGIN
IF EXISTS(SELECT 1 FROM OPENJSON(@info) WHERE [key] = 'name') PRINT 'Yes'
ELSE PRINT 'No'
END
New JSON features in SQL Server 2022:
Starting from SQL Server 2022, you may use JSON_PATH_EXISTS()
function to check whether a specified JSON path exists:
DECLARE @info NVARCHAR(100)='{"name":"John","skills":["C#","SQL"]}'
IF ISJSON(@info) = 1 BEGIN
IF JSON_PATH_EXISTS(@info, '$.name') = 1 PRINT 'Yes'
ELSE PRINT 'No'
END
IF
but a condition inWHERE
. If you want to check for the existence of a specific property you don't need to use ISJSON first. UseJSON_VALUE
and check its return value – Santanasantayana