Home > Database > Mysql Tutorial > How to Split Delimited Values in a SQL Column into Multiple Rows?

How to Split Delimited Values in a SQL Column into Multiple Rows?

Patricia Arquette
Release: 2025-01-03 18:33:43
Original
314 people have browsed it

How to Split Delimited Values in a SQL Column into Multiple Rows?

Splitting Delimited Values in a SQL Column into Multiple Rows

In situations where a SQL column contains delimited data, it may be necessary to extract and format the values into multiple rows. This task becomes especially challenging when dealing with large volumes of data or extremely long delimited strings.

Consider the following example:

Source Table

message-id recipient-address
[email protected] [email protected]
[email protected] [email protected]
[email protected] [email protected];[email protected];[email protected]

Desired Output

message-id recipient-address
[email protected] [email protected]
[email protected] [email protected]
[email protected] [email protected]
[email protected] [email protected]
[email protected] [email protected]

For SQL Server versions 2016 and above, the STRING_SPLIT function provides a straightforward solution:

SELECT s.[message-id], f.value
FROM dbo.SourceData AS s
CROSS APPLY STRING_SPLIT(s.[recipient-address], ';') AS f;
Copy after login

Prior to SQL Server 2016, a custom split function can be created:

CREATE FUNCTION dbo.SplitStrings
(
    @List NVARCHAR(MAX),
    @Delimiter NVARCHAR(255)
)
RETURNS TABLE
AS
RETURN (SELECT Number = ROW_NUMBER() OVER (ORDER BY Number),
        Item FROM (SELECT Number, Item = LTRIM(RTRIM(SUBSTRING(@List, Number,
        CHARINDEX(@Delimiter, @List + @Delimiter, Number) - Number)))
    FROM (SELECT ROW_NUMBER() OVER (ORDER BY s1.[object_id])
        FROM sys.all_objects AS s1 CROSS APPLY sys.all_objects) AS n(Number)
    WHERE Number <= CONVERT(INT, LEN(@List))
        AND SUBSTRING(@Delimiter + @List, Number, 1) = @Delimiter
    ) AS y);
GO
Copy after login

With the split function in place, the data can be extracted and formatted:

SELECT s.[message-id], f.Item
FROM dbo.SourceData AS s
CROSS APPLY dbo.SplitStrings(s.[recipient-address], ';') AS f;
Copy after login

By leveraging these techniques, it is possible to efficiently split delimited values into multiple rows, simplifying data formatting and analysis tasks.

The above is the detailed content of How to Split Delimited Values in a SQL Column into Multiple Rows?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template