简体   繁体   English

T-SQL函数将带有两个定界符的字符串拆分为表中的列分隔符

[英]T-SQL function to split string with two delimiters as column separators into table

I'm looking for a t-sql function to get a string like: 我正在寻找一个t-sql函数来获取类似这样的字符串:

a:b,c:d,e:f a:b,c:d,e:f

and convert it to a table like 并将其转换为像

ID     Value

a      b

c      d

e      f

Anything I found in Internet incorporated single column parsing (eg XMLSplit function variations) but none of them letting me describe my string with two delimiters, one for column separation & the other for row separation. 我在Internet上发现的所有内容都包含单列解析(例如XMLSplit函数变体),但是它们都不能让我用两个定界符描述我的字符串,一个定界符用于列分隔,另一个定于行分隔。

Can you please guiding me regarding the issue? 您能在这个问题上指导我吗? I have a very limited t-sql knowledge and cannot fork those read-made functions to get two column solution? 我对t-sql的知识非常有限,无法分叉这些现成的函数来获取两列解决方案?

You can find a split() function on the web. 您可以在网上找到split()函数。 Then, you can do string logic: 然后,您可以执行字符串逻辑:

select left(val, charindex(':', val)) as col1,
       substring(val, charindex(':', val) + 1, len(val)) as col2
from dbo.split(@str, ';') s(val);

You can use a custom SQL Split function in order to separate data-value columns Here is a sql split function that you can use on a development system It returns an ID value that can be helpful to keep id and value together 您可以使用自定义的SQL Split函数来分隔数据值列这是一个sql split函数 ,您可以在开发系统上使用它返回一个ID值,该值有助于将ID和值保持在一起

You need to split twice, first using "," then a second split using ";" 您需要拆分两次,首先使用“,”,然后第二次使用“;” character 字符

declare @str nvarchar(100) = 'a:b,c:d,e:f'
select
    id = max(id),
    value = max(value)
from (
select 
    rowid,
    id = case when id = 1 then val else null end,
    value = case when id = 2 then val else null end
from (
select 
    s.id rowid, t.id, t.val
from (
    select * from dbo.Split(@str, ',')
) s
cross apply dbo.Split(s.val, ':') t
) k
) m group by rowid

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

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