简体   繁体   English

SQL Server - 将逗号分隔的字符串列转换为JSON数组到新列

[英]SQL Server - convert a column of comma-separated string to JSON array into a new column

I have a SQL Server database with a column called Categories containing comma-separated values in the format nvarchar(50) . 我有一个SQL Server数据库,其中一个名为Categories的列包含格式为nvarchar(50)逗号分隔值。 The length of each column is variable from record to record. 每列的长度在记录之间是可变的。

I've created a new empty column called CategoriesJSONArray . 我创建了一个名为CategoriesJSONArray的新空列。 For all existing records, I need to convert the values in Categories to JSON arrays and write those converted values to CategoriesJSONArray . 对于所有现有记录,我需要将Categories的值转换为JSON数组,并将这些转换后的值写入CategoriesJSONArray

How would I accomplish this using T-SQL, or from within the SSMS UI? 我如何使用T-SQL或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"}

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: 有一些方法可以将分隔的字符串拆分成记录,然后将这些字符串聚合回JSON,但我认为这里的一些连接和替换会更容易:

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. 这可能需要一些调整来处理空间和诸如此类的东西,如果你的JSON变得更复杂,它显然是行不通的,但它很快而且很脏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM