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;
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);
Data Manipulation:
SELECT s.[message-id], f.Item FROM dbo.SourceData AS s CROSS APPLY dbo.SplitStrings(s.[recipient-address], ';') as f;
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!