将 SQL 列中的分隔值拆分为多行
在 SQL 列包含分隔数据的情况下,可能需要提取并将值格式化为多行。在处理大量数据或极长的分隔字符串时,此任务变得尤其具有挑战性。
考虑以下示例:
源表
message-id | recipient-address |
---|---|
[email protected] | [email protected] |
[email protected] | [email protected] |
[email protected] | [email protected];[email protected];[email protected] |
想要的输出
message-id | recipient-address |
---|---|
[email protected] | [email protected] |
[email protected] | [email protected] |
[email protected] | [email protected] |
[email protected] | [email protected] |
[email protected] | [email protected] |
对于 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 2016 之前,可以使用自定义拆分函数创建:
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
使用 split 函数,可以提取数据并格式化:
SELECT s.[message-id], f.Item FROM dbo.SourceData AS s CROSS APPLY dbo.SplitStrings(s.[recipient-address], ';') AS f;
通过利用这些技术,可以有效地将分隔值拆分为多行,从而简化数据格式化和分析任务。
以上是如何将 SQL 列中的分隔值拆分为多行?的详细内容。更多信息请关注PHP中文网其他相关文章!