SQL 提取给定字符串的两个逗号之间的字符串,并拆分成两列的键值对

SQL Extract string between two comma for a given string and split in key value pair of two columns

我在一个字段中连接了以下值(我将它们分开了)

--,\r\n  \"Indie_163\": \"\",
--,\r\n  \"Pop_197\": null,
--,\r\n  \"Mgr_206\": \"Mark Timberland\",
--,\r\n  \"Date_225\": \"02/28/2019\"
--,\r\n  \"Fees_200\": \"57500\",

字段中的实际值:

 {\"Indie_163\": \"\","Pop_197\": null,\r\n  \"Mgr_206\": \"Mark Timberland\",\r\n  \"Date_225\": \"02/28/2019\",\r\n  \"Fees_200\": \"57500\"})

需要将它们拆分为 5 个键值对值列:

Indie_Key | Indie_Val | Pop_Key | Pop_Val | Mgr_Key | Mgr_Val | Date_Key | Date_Val | Fees_Key | Fees_Val

它应该将键和值填充为(空白''、空值或双引号内拆分 (:) 之后的值)

注意:列 - 'Indie_'、'Pop_'、'Mgr_'、'Date_'、'Fees_' 是固定字符串,后缀数字可以更改

您的数据看起来像是编码错误的 json 值。您可以使用 replace(replace(x, '\"', '"'), '\r\n', '')

修复这些问题

OPENJSON T-SQL 函数让您查询 json 值。有关更多信息,请访问 MSDN

让我们为您提供以下数据:

DECLARE @data TABLE (ID int, x nvarchar(max))
INSERT INTO @data
VALUES
    (1, ' {\"Indie_163\": \"A\","Pop_197\": null,\r\n  \"Mgr_206\": \"Mark Timberland\",\r\n  \"Date_225\": \"02/28/2019\",\r\n  \"Fees_200\": \"57500\"})'),
    (2, ' {\"Indie_163\": \"B\","Pop_197\": null,\r\n  \"Mgr_206\": \"Mark X\",\r\n  \"Date_225\": \"02/28/2017\",\r\n  \"Fees_200\": \"57501\"})'),
    (3, ' {\"Indie_164\": \"C\","Pop_197\": \"D\",\r\n  \"Mgr_206\": \"Mark Y\",\r\n  \"Date_225\": \"02/28/2018\",\r\n  \"Fees_200\": \"57502\"})')

您可以使用

查询它们
SELECT * 
FROM @data
    CROSS APPLY openjson(replace(replace(x, '\"', '"'), '\r\n', '')) x 

哪个会产生这个

然后你可以像这样查询你想要的每个字段:

SELECT id, 
    MAX(Pop_KEY)    POP_KEY,    MAX(Pop_VALUE)      Pop_VALUE,
    MAX(Indie_KEY)  Indie_KEY,  MAX(Indie_VALUE)    Indie_VALUE,
    MAX(Date_KEY)   Date_KEY,   MAX(Date_VALUE)     Date_VALUE,
    MAX(Fees_KEY)   Fees_KEY,   MAX(Fees_VALUE)     Fees_VALUE
FROM (
    SELECT id, 
        IIF(charindex('Pop',   [key]) = 1, [key],null) as Pop_KEY,   IIF( charindex('Pop',   [key]) = 1, [value],null) as Pop_VALUE,
        IIF(charindex('Indie', [key]) = 1, [key],null) as Indie_KEY, IIF( charindex('Indie', [key]) = 1, [value],null) as Indie_VALUE,
        IIF(charindex('Date',  [key]) = 1, [key],null) as Date_KEY,  IIF( charindex('Date',  [key]) = 1, [value],null) as Date_VALUE,
        IIF(charindex('Fees',  [key]) = 1, [key],null) as Fees_KEY,  IIF( charindex('Fees',  [key]) = 1, [value],null) as Fees_VALUE
    FROM @data
    CROSS APPLY openjson(replace(replace(x, '\"', '"'), '\r\n', '')) x 
) t
GROUP BY id

这将产生