0

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

Md. Parvez Alam
  • 4,326
  • 5
  • 48
  • 108
  • You should at least post some information about the table structure, the desired JSON output and about what you've tried so far. – Onkel Toob Apr 09 '18 at 12:14
  • I have done google but din't find any example showing single value in json array, its using key value pairs – Md. Parvez Alam Apr 09 '18 at 12:15
  • `SELECT * FROM OPENJSON('[1,2,3,4]') WITH ([value] INT '$')`; `SELECT '[' + STRING_AGG([value],',') + ']' FROM (SELECT * FROM OPENJSON('[1,2,3,4]') WITH ([value] INT '$') EXCEPT SELECT 3) _`. In short: don't do this if you can help it. Use properly normalized tables if updating is something you'll be doing frequently. JSON support is not there as a way to support improperly normalized tables. Even if your input is primarily JSON, it's trivial to convert tables back to JSON, so that's not really an excuse. – Jeroen Mostert Apr 09 '18 at 12:45

1 Answers1

0

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.

Onkel Toob
  • 2,152
  • 1
  • 17
  • 25