Home > Database > Mysql Tutorial > How to Efficiently Split Delimited Strings in T-SQL?

How to Efficiently Split Delimited Strings in T-SQL?

Mary-Kate Olsen
Release: 2025-01-23 08:41:11
Original
609 people have browsed it

How to Efficiently Split Delimited Strings in T-SQL?

Efficiently Splitting Delimited Strings in T-SQL

This article explores efficient techniques for separating comma-delimited strings (e.g., "1,2,3,4,5") into individual rows within a T-SQL table or table variable. Two effective methods are detailed below:

Method 1: XML Parsing

This approach leverages T-SQL's XML parsing capabilities for a concise solution:

<code class="language-sql">DECLARE @xml xml, @str varchar(100), @delimiter varchar(10)

SET @str = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15'
SET @delimiter = ','
SET @xml = cast(('<X>'+replace(@str, @delimiter, '</X><X>')+'</X>') as xml)

SELECT C.value('.', 'varchar(10)') as value FROM @xml.nodes('X') as X(C)</code>
Copy after login

Method 2: Recursive CTE

For those preferring a recursive Common Table Expression (CTE) approach:

<code class="language-sql">DECLARE @str varchar(100), @delimiter varchar(10)

SET @str = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15'
SET @delimiter = ','

;WITH cte AS
(
    SELECT 0 a, 1 b
    UNION ALL
    SELECT b, CHARINDEX(@delimiter, @str, b) + LEN(@delimiter)
    FROM CTE
    WHERE b > a
)
SELECT SUBSTRING(@str, a,
CASE WHEN b > LEN(@delimiter) 
    THEN b - a - LEN(@delimiter) 
    ELSE LEN(@str) - a + 1 END) value      
FROM cte WHERE a > 0</code>
Copy after login

Both methods offer efficient string splitting, allowing for subsequent data processing and analysis. For more complex string manipulation, consult specialized T-SQL string functions and advanced techniques.

The above is the detailed content of How to Efficiently Split Delimited Strings in T-SQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template