我在一个字段中连接了以下值(我已经拆分了它们)
--,\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
它应该将 Keys 和 value 填充为 (Blank '', null, or values come after split (:) 在双引号内)
注意:列 - '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
这将产生
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句