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

How to Split Comma-Delimited Strings in T-SQL?

Susan Sarandon
Susan SarandonOriginal
2025-01-23 08:36:11922browse

How to Split Comma-Delimited Strings in T-SQL?

Efficiently Parsing Comma-Delimited Strings in T-SQL

T-SQL lacks a built-in split function, unlike many other programming languages. However, several techniques effectively achieve string splitting.

Approach 1: Leveraging XML Parsing

This approach uses XML's inherent parsing capabilities to separate values. The following T-SQL code illustrates this:

<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>

Approach 2: CTE and CHARINDEX for Recursive Splitting

This method employs a Common Table Expression (CTE) and the CHARINDEX function for recursive string splitting:

<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>

Further Exploration

For additional methods and a broader discussion on splitting comma-delimited strings within T-SQL, consult this helpful resource:

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

Statement:
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