简体   繁体   English

SQL-将具有多个定界符的字符串拆分为多行和多列

[英]SQL - Split string with multiple delimiters into multiple rows and columns

I am trying to split a string in SQL with the following format: 'John, Mark, Peter|23, 32, 45' . 我正在尝试使用以下格式在SQL中拆分字符串: 'John, Mark, Peter|23, 32, 45'

The idea is to have all the names in the first columns and the ages in the second column. 想法是在第一列中包含所有名称,在第二列中包含年龄。

在此处输入图片说明

The query should be "dynamic", the string can have several records depending on user entries. 该查询应该是“动态的”,该字符串可以具有多个记录,具体取决于用户条目。

Does anyone know how to this, and if possible without SQL functions? 有谁知道如何做到这一点,如果可能的话,没有SQL函数? I have tried the cross apply approach but I wasn't able to make it work. 我尝试了交叉应用方法,但无法使其正常工作。

Any ideas? 有任何想法吗?

This solution uses Jeff Moden's DelimitedSplit8k . 该解决方案使用Jeff Moden的DelimitedSplit8k Why? 为什么? Because his solution provides the ordinal position of the item. 因为他的解决方案提供了项目的顺序位置 Ordinal Position something that many others functions, including Microsoft's own STRING_SPLIT , does not provide. 顺序定位某些其他功能(包括Microsoft自己的STRING_SPLIT )不提供的功能。 It's going to be vitally important for getting this to work correctly. 为了使其正常工作,这至关重要。

Once you have that, the solution becomes fairly simple: 一旦有了这些,解决方案就变得非常简单:

DECLARE @NameAges varchar(8000) = 'John, Mark, Peter|23, 32, 45';

WITH Splits AS (
    SELECT S1.ItemNumber AS PipeNumber,
           S2.ItemNumber AS CommaNumber,
           S2.Item
    FROM dbo.DelimitedSplit8K (REPLACE(@NameAges,' ',''), '|') S1 --As you have spaces between the delimiters I've removed these. Be CAREFUL with that
         CROSS APPLY DelimitedSplit8K (S1.item, ',') S2)
SELECT S1.Item AS [Name], 
       S2.Item AS Age
FROM Splits S1
     JOIN Splits S2 ON S1.CommaNumber = S2.CommaNumber
                   AND S2.PipeNumber = 2
WHERE S1.PipeNumber = 1;

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

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