4

I have a SQL Server database with a column called Categories containing comma-separated values in the format nvarchar(50). The length of each column is variable from record to record.

I've created a new empty column called CategoriesJSONArray. For all existing records, I need to convert the values in Categories to JSON arrays and write those converted values to CategoriesJSONArray.

How would I accomplish this using T-SQL, or from within the SSMS UI?

EDIT: example, as requested

Current:

Record   Categories

1        Sales, Support, Growth
2        Sales, Growth
3        Sales
4        Support, Growth, Sustain

Desired:

Record   Categories                  CategoriesJSONArray

1        Sales, Support, Growth      { "Sales" : "Support" : "Growth"}
2        Sales, Growth               { "Sales" : "Growth"}
3        Sales                       { "Sales" }
4        Support, Growth, Sustain    { "Sales" : "Growth" : "Sustain"}
9
  • 1
    Why don't you use a stored procedure to split the column based on the , and return it as a table. Commented May 12, 2017 at 15:25
  • This a good suggestion, let me look into this approach. Commented May 12, 2017 at 15:27
  • Sample data and desired results would be helpful Commented May 12, 2017 at 15:30
  • 1
    The root of the issue is that you are storing delimited values in a single tuple. This violates 1NF and causes untold amounts of anguish. You will have to split those values first into a table. Here is an article with a number of excellent solutions to this problem. sqlperformance.com/2012/07/t-sql-queries/split-strings Commented May 12, 2017 at 15:33
  • @JohnCappelletti question updated with example. Commented May 12, 2017 at 15:57

1 Answer 1

4

There's some ways to split a delimited string into records and then aggregate those back into JSON, but I think some concatenation and replacing would be a easier here:

SELECT record,
    Categories,
    '{"' + REPLACE(Categories, ', ', '":"') + '"}' as CategoriesJSONArray
FROM table

That may need some tweaking to deal with spaces and whatnot and it obviously won't work if your JSON becomes more complex, but it's quick and dirty.

Sign up to request clarification or add additional context in comments.

4 Comments

Beat me by seconds
I saw that, but yours was prettier! I'm glad that I am in good company with the solution though, I thought for sure it was too quick and dirty for SO with all the fancy strtok procedures and json-erizing that could be done.
I just added a space after the comma in the string literal. I think that ought to get rid of those.
@JNevill definitely makes sense, thanks! I'll test it out now and assuming all goes well I'll mark yours as the answer.

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.