I am storing ids in comma separated string.
e.g
1,2,3,4
How can I store this in JSON in the column and should be able to insert delete any particular value?
Thanks
I am storing ids in comma separated string.
e.g
1,2,3,4
How can I store this in JSON in the column and should be able to insert delete any particular value?
Thanks
Part of the following answer comes from here, so all credits go there: https://stackoverflow.com/a/37844117/2695832
Here's a solution that enables you to store your string values in a JSON array in a table column. However, the should be able to insert delete any particular value part of your question is not totally clear to me.
DECLARE @source VARCHAR(20);
SET @source = '1,2,3,4';
DECLARE @values TABLE
(
[Id] VARCHAR(20)
);
INSERT INTO @values
(
[Id]
)
SELECT
value
FROM [STRING_SPLIT](@source, ',')
WHERE RTRIM(value) <> '';
INSERT INTO @values ([Id]) VALUES ('5')
DELETE FROM @values WHERE Id = 2
SELECT
JSON_QUERY('[' + STUFF(( SELECT ',' + '"' + Id + '"'
FROM @values FOR XML PATH('')),1,1,'') + ']' ) ids
FOR JSON PATH , WITHOUT_ARRAY_WRAPPER
This produces the following JSON object:
{"ids":["1","3","4","5"]}
The code might need some tweaking to completely match your needs since you're probably not using a table variable and also maybe want to use a numeric data type for your id values.