0

I have the following (minimal) example

-- prepare some data
DECLARE @src TABLE (txt varchar(MAX), id bigint)
insert into @src (txt, id) values ('foo', 1)
insert into @src (txt, id) values ('bar', 1)
insert into @src (txt, id) values ('baz', 1)
insert into @src (txt, id) values ('foo', 2)
insert into @src (txt, id) values ('bar', 2)

-- prepare json 
declare @dst TABLE (json varchar(max), id bigint)
insert into @dst (json, id) values ('[]', 1)
insert into @dst (json, id) values ('[]', 2)

-- peek the expected result
select s.txt, d.id from @src s 
inner join @dst d
on d.id = s.id

-- now update
update @dst set json = JSON_MODIFY(d.json, 'append strict $', s.txt)
from @src s 
inner join @dst d
on d.id = s.id

-- let's see
select * from @dst

I would expect the result to be ['foo', 'bar', 'baz'] for id 1 in the @dst table. I have one very similar case in which this works but I can't get it working again.

What am I missing here?

1 Answer 1

1

In your case, the UPDATE statement is not deterministic, because the statement includes a FROM clause that returns more than one value for the json column. This is explained in the "Best practices" part of the documentation: Use caution when specifying the FROM clause to provide the criteria for the update operation. The results of an UPDATE statement are undefined if the statement includes a FROM clause that is not specified in such a way that only one value is available for each column occurrence that is updated, that is if the UPDATE statement is not deterministic.

But you may change your approach and build the expected JSON array with STRING_AGG() or FOR XML PATH(if STRING_AGG() is not available). Notice, that you can't build a JSON array of scalar values using FOR JSON.

UPDATE @dst
SET json = a.json
FROM @dst d
CROSS APPLY (
   SELECT CONCAT('[', STRING_AGG('"' + txt + '"', ','), ']') AS json
   FROM @src s
   WHERE s.id = d.id
) a

Result:

json                id
----------------------
["foo","bar","baz"] 1
["foo","bar"]       2
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.