嘗試將值分割為多個行時,SQL 資料列中的分隔符號可能會帶來挑戰行。本文提供了針對最新版本和舊版 SQL Server 的解決方案。
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;
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中文網其他相關文章!