将 SQL 列中的分隔值拆分为多行
问题陈述:
插入 Exchange 2007 时邮件跟踪记录到 SQL 表中,收件人位于分隔的收件人地址列中有时包含多个值。用户希望将这些值拆分为另一个表中的单独行,同时保持原始消息 ID 关联。
解决方案:
SQL Server 2016
利用新的 STRING_SPLIT函数:
SELECT s.[message-id], f.value FROM dbo.SourceData AS s CROSS APPLY STRING_SPLIT(s.[recipient-address], ';') as f;
SQL Server Pre-2016
创建自定义分割函数 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);
数据操作:
SELECT s.[message-id], f.Item FROM dbo.SourceData AS s CROSS APPLY dbo.SplitStrings(s.[recipient-address], ';') as f;
以上是如何将 SQL 中的分隔收件人地址拆分为多行?的详细内容。更多信息请关注PHP中文网其他相关文章!