2

Is it possible to change the values of sub-json-data in the following manner?

DECLARE @json NVARCHAR(MAX) = "{"message":"Machine is down","machineId":"165ACE37-4E2C-4D44-9D14-F9E2CB2C2C13","machineName":"1501","ipAddress":"192.168.150.101","time":"2018-05-20T18:33:23.171"}"

SELECT * FROM OPENJSON(@json) 
WITH (  message varchar(200) '$.message',
    machineId varchar(200) '$.machineId',
    machineName int '$.machineName',
    ipAddress varchar(200) '$.ipAddress',
    LocalTime datetime2(7) '$.time'
) AS ChangeTime

I want to change the LocalTime variable i created and then replace the current one.

I want to remove two hours from the $.time parameter.

Something like this:

UPDATE Table SET ChangeTime.LocalTime = DATEADD(hour,-2,ChangeTime.LocalTime)

Input: " time":"2018-05-20T18:33:23.171"

output: "time":"2018-05-20T16:33:23.171"

How would i accomplish this?

2 Answers 2

4

You could use JSON_MODIFY:

Updates the value of a property in a JSON string and returns the updated JSON string.

SET @json=JSON_MODIFY(@json,'$.time',
   FORMAT(DATEADD(hour,-2,JSON_VALUE(@json,'$.time')),'yyyy-MM-ddTHH:mm:ss.fff'));

SELECT * FROM OPENJSON(@json) 
WITH (  message varchar(200) '$.message',
    machineId varchar(200) '$.machineId',
    machineName int '$.machineName',
    ipAddress varchar(200) '$.ipAddress',
    LocalTime datetime2(7) '$.time'
) AS ChangeTime;

DBFIddle Demo

2
  • Perfect! However, how would i execute the query to replace the current db-entry?
    – Joel
    Commented Jun 20, 2018 at 8:47
  • @Joel exactly the same. Just put UPDATE tab SET my_json_column = JSON_MODIFY(my_json_column,'$.time', FORMAT(DATEADD(hour,-2,JSON_VALUE(my_json_column,'$.time')),'yyyy-MM-ddTHH:mm:ss.fff')) Commented Jun 20, 2018 at 8:48
0

Maybe something like this:

LocalTime - INTERVAL '2 hours'

With interval you can remove or add any time denomination. Like days, months, years, seconds etc

WITH (  message varchar(200) '$.message',
    machineId varchar(200) '$.machineId',
    machineName int '$.machineName',
    ipAddress varchar(200) '$.ipAddress',
    LocalTime datetime2(7) '$.time'
) AS ChangeTime
SELECT LocalTime - INTERVAL '2 hours'
FROM ChangeTime
4
  • I'll look into it. However, a problem i have is that There is no such variable as ChangeTime.LocalTime. How would i access the parameter within the with clause?
    – Joel
    Commented Jun 20, 2018 at 8:22
  • Could you not update it outside of the with? I'll update me answer, hold on Commented Jun 20, 2018 at 8:24
  • Yeah, right now i'm just parsing out the JSON data into objects, so that i can run DATEADD on the field. After that I want to replace (or update) the current entry with the new value
    – Joel
    Commented Jun 20, 2018 at 8:25
  • Sorry, but i can't reach any variables within the with clause still.
    – Joel
    Commented Jun 20, 2018 at 8:38

Not the answer you're looking for? Browse other questions tagged or ask your own question.