Home > Database > Mysql Tutorial > How to Split Delimited Recipient Addresses in SQL into Multiple Rows?

How to Split Delimited Recipient Addresses in SQL into Multiple Rows?

DDD
Release: 2024-12-31 19:18:11
Original
634 people have browsed it

How to Split Delimited Recipient Addresses in SQL into Multiple Rows?

Splitting Delimited Values in a SQL Column into Multiple Rows

Problem Statement:
When inserting Exchange 2007 Message Tracking logs into a SQL table, recipients in the delimited recipient-address column sometimes contain multiple values. The user wants to split these values into separate rows in another table while maintaining the original message-id association.

Solution:

SQL Server 2016
Utilizing the new STRING_SPLIT function:

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

SQL Server Pre-2016
Creating a custom split function dbo.SplitStrings:

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);
Copy after login

Data Manipulation:

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

The above is the detailed content of How to Split Delimited Recipient Addresses in SQL 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template