[英]Split string with multiple delimiters into columns in SQL Server
I have data in my SQL Server table in string format that looks like this:我的 SQL 服务器表中有字符串格式的数据,如下所示:
Sample data样本数据
create table Test (
resource_type varchar(300)
);
insert into Test (resource_type) values
('account_id:535533456241,resource_type:buckets,resource_name:tni-prod-diva-backups'),
('account_id:460085747812,resource_type:buckets,resource_name:bda-sit-tims'),
('account_id:123456789012,resource_type:buckets,resource_name:fi.fa.foo.bar.baz');
I want a SQL query to get an output like this:我想要一个 SQL 查询来获得这样的 output :
account_id![]() |
resource_type![]() |
resource_name![]() |
---|---|---|
535533456241 ![]() |
buckets![]() |
tni-prod-diva-backups ![]() |
460085747812 ![]() |
buckets![]() |
bda-sit-tims ![]() |
123456789012 ![]() |
buckets![]() |
fi.fa.foo.bar.baz ![]() |
I am working with this code, but its not giving me the expected output.我正在使用此代码,但它没有给我预期的 output。 Could someone help?
有人可以帮忙吗?
SELECT
REVERSE(PARSENAME(REPLACE(REVERSE([resource_type]), ',', '.'), 1)) AS [Street],
REVERSE(PARSENAME(REPLACE(REVERSE([resource_type]), ',', '.'), 2)) AS [Street],
REVERSE(PARSENAME(REPLACE(REVERSE([resource_type]), ',', '.'), 3)) AS [Street]
FROM
[Test].[CloudHealth]
Output of this query:此查询的 Output:
If that string is transformed back to a JSON format, then it's possible to process it like a json.如果将该字符串转换回 JSON 格式,则可以像 json 一样处理它。
SELECT
JSON_VALUE(json, '$.account_id') AS [account_id]
, JSON_VALUE(json, '$.resource_type') AS [resource_type]
, JSON_VALUE(json, '$.resource_name') AS [resource_name]
FROM Test t
CROSS APPLY (VALUES('{"'+REPLACE(REPLACE(STRING_ESCAPE(t.resource_type,'json'),':','":"'),',','","') +'"}')) ca(json)
account_id 帐户ID
resource_type 资源类型
resource_name 资源名称
535533456241 535533456241
buckets 水桶
tni-prod-diva-backups tni-prod-diva 备份
460085747812 460085747812
buckets 水桶
bda-sit-tims bda-sit-tims
123456789012 123456789012
buckets 水桶
fi.fa.foo.bar.baz fi.fa.foo.bar.baz
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.