T Sql Split String On Delimiter

5 min read

Introduction

When you need to t sql split string on delimiter, you are essentially looking for a way to break a single text value into multiple parts based on a specific character or set of characters. This operation is fundamental in data cleaning, reporting, and any scenario where delimited data resides inside a single column of a relational table. Think about it: in SQL Server, the most straightforward approach is the built‑in STRING_SPLIT function, which handles the t sql split string on delimiter task with minimal code. This article walks you through the concept, the step‑by‑step process, alternative techniques, and performance tips so you can confidently split strings in any T‑SQL environment.

Understanding Delimiters

A delimiter is the character (or sequence of characters) that separates each element of the string you want to break apart. Recognizing the delimiter is crucial because it determines how the string will be parsed and how the resulting pieces will be stored (e.Day to day, common delimiters include commas (,), semicolons (;), pipes (|), and spaces. Think about it: the choice of delimiter depends on the source data format. In real terms, g. As an example, CSV files use commas, while log files might use pipes. , in a temporary table or a table variable).

Key points:

  • Delimiter definition – a single character or multi‑character token.
  • Consistency – the same delimiter must appear between every element for reliable splitting.
  • Edge cases – leading/trailing delimiters, empty elements, or duplicate delimiters can affect results.

Basic Method: STRING_SPLIT

The simplest way to t sql split string on delimiter in modern SQL Server (2016 and later) is to use the STRING_SPLIT function. It returns a one‑dimensional table containing each element as a separate row It's one of those things that adds up. Worth knowing..

Syntax

STRING_SPLIT ( string_expression , delimiter )
  • string_expression – the text you want to split.
  • delimiter – the character that separates the parts (e.g., ',').

Example

DECLARE @csv NVARCHAR(100) = 'apple,banana,cherry,date';

SELECT value
FROM   STRING_SPLIT(@csv, ',')

Result:

value
apple
banana
cherry
date

The query above demonstrates t sql split string on delimiter using a comma. Each element appears as an individual row, ready for further processing (joining, aggregating, inserting, etc.).

Step‑by‑Step Guide Using STRING_SPLIT

  1. Identify the source column that contains the delimited text.
  2. Choose the appropriate delimiter based on the data format.
  3. Call STRING_SPLIT with the column and delimiter.
  4. Optionally filter or aggregate the resulting rows (e.g., WHERE value <> '' to drop empty items).
  5. Join the split result back to the original table if you need to retain other column data.

Detailed Example

Assume a table FruitOrders with columns OrderID (int) and FruitList (nvarchar(200)) storing a comma‑separated list of fruits for each order.

SELECT  o.OrderID,
        f.value AS Fruit
FROM    dbo.FruitOrders AS o
CROSS APPLY STRING_SPLIT(o.FruitList, ',') AS f
WHERE   f.value <> '';   -- removes any empty strings caused by trailing commas
  • CROSS APPLY ensures the split rows are matched to each original order.
  • The WHERE clause handles cases where the source string ends with a delimiter, which would otherwise produce an empty row.

Alternative Approaches

While STRING_SPLIT is convenient, older SQL Server versions (pre‑2016) lack this function. In those environments you can employ other techniques to achieve t sql split string on delimiter.

1. Using a Tally (Numbers) Table

A numbers table provides a set of sequential integers that can be used to locate each delimiter via CHARINDEX and extract substrings with SUBSTRING.

DECLARE @str NVARCHAR(100) = 'red,green,blue,yellow';
DECLARE @delimiter CHAR(1) = ',';

;WITH Split(Start, End, Length) AS (
    SELECT 1,
           CHARINDEX(@delimiter, @str) ,
           CASE CHARINDEX(@delimiter, @str)
                WHEN 0 THEN LEN(@str)
                ELSE CHARINDEX(@delimiter, @str)
           END
    UNION ALL
    SELECT End + 1,
           CASE WHEN CHARINDEX(@delimiter, @str, End + 1) = 0 
                THEN LEN(@str) 
                ELSE CHARINDEX(@delimiter, @str, End + 1) 
           END,
           CASE WHEN CHARINDEX(@delimiter, @str, End + 1) = 0 
                THEN LEN(@str) - End 
                ELSE CHARINDEX(@delimiter, @str, End + 1) - End - 1 
           END
    FROM Split
    WHERE End <= LEN(@str)
)
SELECT 'Item' + CAST(ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS VARCHAR(10)) AS Fruit,
       SUBSTRING(@str, Start, Length) AS Value
FROM Split;

This method mimics t sql split string on delimiter by iteratively finding the next delimiter position and extracting the substring between two delimiters It's one of those things that adds up..

2. Recursive CTE – a pure‑T‑SQL solution
When a permanent tally table is unavailable, a recursive CTE can generate the positions of each delimiter on the fly. The idea is to start at the first character, locate the next comma, return the substring up to that point, then continue from the character after the delimiter No workaround needed..

DECLARE @txt NVARCHAR(200) = 'apple, banana,cherry, date';

;WITH Split AS (
    SELECT 1 AS pos,
           CAST('' + @txt AS XML) AS data,
           '' AS remaining
    UNION ALL
    SELECT pos + 1,
           data,
           SUBSTRING(remaining,
                     pos + 1,
                     CASE 
                         WHEN CHARINDEX(',', remaining, pos + 1) = 0 
                              THEN LEN(remaining) 
                         ELSE CHARINDEX(',', remaining, pos + 1) 
                     END - pos - 1)
    FROM Split
    WHERE CHARINDEX(',', remaining, pos) > 0
       OR pos = 1
)
SELECT 'Fruit' + CAST(pos AS VARCHAR(10)) AS Fruit,
       LTRIM(RTRIM(value)) AS FruitName
FROM (
    SELECT pos,
           SUBSTRING(data, 1, 
                     CASE 
                         WHEN CHARINDEX(',', data, pos) = 0 
                              THEN LEN(data) 
                         ELSE CHARINDEX(',', data, pos) 
                     END) AS value
    FROM Split
) AS s
ORDER BY pos;

The recursive CTE walks through the string, extracts each piece, trims any surrounding blanks, and returns a tidy result set. Because the logic is set‑based, it scales better than a looping cursor, though it still lags behind the native STRING_SPLIT in raw speed Most people skip this — try not to..

3. XML‑based splitting
SQL Server’s XML data type provides a compact way to split delimited strings without resorting to loops or tally tables. By converting the list into an XML fragment and using the .nodes() method, each item can be extracted as a separate row.

DECLARE @list NVARCHAR(100) = 'red,green,blue,yellow';

SELECT LTRIM(RTRIM(value)) AS Item
FROM (
    SELECT CAST(''+REPLACE(@list, ',', '')+'
Fresh Picks

Just Went Online

Explore the Theme

You Might Want to Read

Thank you for reading about T Sql Split String On Delimiter. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home