將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] |
想要的輸出
SELECT s.[message-id], f.value FROM dbo.SourceData AS s CROSS APPLY STRING_SPLIT(s.[recipient-address], ';') AS f;
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
SELECT s.[message-id], f.Item FROM dbo.SourceData AS s CROSS APPLY dbo.SplitStrings(s.[recipient-address], ';') AS f;
以上是如何將 SQL 欄位中的分隔值拆分為多行?的詳細內容。更多資訊請關注PHP中文網其他相關文章!