TechBuzzPro

How to Split a String by a Delimiter in SQL Server

· 6 min read · Apps & Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

In SQL Server, splitting a string by a delimiter (like a comma, semicolon, or pipe) is a common task when you need to break a delimited list into individual rows or values. This guide shows you the most practical methods, from the built-in STRING_SPLIT function (SQL Server 2016 and later) to older alternatives like recursive CTEs and XML. You'll learn how to write the queries, handle edge cases, and avoid common pitfalls.

What You'll Need

  • SQL Server 2016 or later for the STRING_SPLIT function (recommended). If you're on an older version, you'll need to use the XML or recursive CTE method.
  • A SQL query editor (SSMS, Azure Data Studio, or any client) connected to your database.
  • A table or variable containing the delimited strings you want to split.

Step-by-Step

  1. Identify your delimiter and your data source.
    Decide what character separates your values (e.g., comma, semicolon, pipe) and where the string lives (a column in a table, a variable, or a literal). For this example, we'll use a comma as the delimiter and a table called Orders with a column ItemList containing values like 'apple,banana,cherry'.
  2. Use the STRING_SPLIT function (SQL Server 2016+).
    The simplest method is the built-in STRING_SPLIT function. It takes two arguments: the input string and the delimiter. It returns a single column named value with each item as a row.
    SELECT value
    FROM STRING_SPLIT('apple,banana,cherry', ',');
    This returns three rows: 'apple', 'banana', 'cherry'.
  3. Split a column from a table.
    To split values from every row in a table, use CROSS APPLY to join the function to each row:
    SELECT o.OrderId, s.value AS Item
    FROM Orders o
    CROSS APPLY STRING_SPLIT(o.ItemList, ',') s;
    This gives you one row per item, with the corresponding OrderId.
  4. If you need the ordinal position of each item (SQL Server 2022+).
    The STRING_SPLIT function added an optional third parameter enable_ordinal in SQL Server 2022. Set it to 1 to get a second column ordinal that shows the position (1-based):
    SELECT value, ordinal
    FROM STRING_SPLIT('apple,banana,cherry', ',', 1);
    This returns: (apple, 1), (banana, 2), (cherry, 3).
  5. If you're on an older version (pre-2016), use a recursive CTE.
    For SQL Server 2008–2014, you can split with a recursive common table expression. This method walks through the string, extracting one item at a time:
    WITH SplitCTE AS (
        SELECT
            CAST('apple,banana,cherry' AS NVARCHAR(MAX)) AS String,
            CHARINDEX(',', 'apple,banana,cherry') AS Pos
        UNION ALL
        SELECT
            CAST(SUBSTRING(String, Pos + 1, LEN(String)) AS NVARCHAR(MAX)),
            CHARINDEX(',', SUBSTRING(String, Pos + 1, LEN(String)))
        FROM SplitCTE
        WHERE Pos > 0
    )
    SELECT
        CASE WHEN Pos > 0 THEN LEFT(String, Pos - 1) ELSE String END AS Item
    FROM SplitCTE;
    This works but is more complex. For most cases, upgrading or using the XML method (below) is easier.
  6. Alternative for older versions: Use XML.
    You can convert the string to XML and then query the nodes. This works on any SQL Server version that supports XML (2005+):
    DECLARE @xml AS XML = '<root><item>apple</item><item>banana</item><item>cherry</item></root>';
    SELECT t.value('.', 'VARCHAR(100)') AS Item
    FROM @xml.nodes('/root/item') AS x(t);
    To generate the XML from your string, replace the commas with </item><item> tags. This method requires careful handling of special characters.
  7. Handle empty values and trailing delimiters.
    STRING_SPLIT ignores empty values by default. If you need to preserve them (e.g., 'apple,,cherry' should yield an empty string between apples and cherries), you'll need a custom splitter or use the XML method with a different approach. For most business cases, ignoring empties is fine.

Common Mistakes

  • Using STRING_SPLIT on SQL Server 2014 or earlier. The function doesn't exist there, so you'll get an error. Use the recursive CTE or XML method instead.
  • Assuming the output column is named 'item' or 'value'. In STRING_SPLIT, the column is always named value. If you alias it, you must use that alias in your SELECT.
  • Forgetting that STRING_SPLIT returns rows, not a single string. If you need to recombine or pivot, you'll need to use other functions like STRING_AGG (2017+) or a pivot.
  • Using the wrong delimiter. If your data uses a pipe or tab, make sure you pass the correct character. A common mistake is using a comma when the data uses a semicolon.
  • Not handling NULL values. If the input string is NULL, STRING_SPLIT returns no rows. You may need to use ISNULL or a default value.

Tips

  • Use CROSS APPLY for table columns. This is the standard pattern and works efficiently with STRING_SPLIT.
  • Check your SQL Server version. Run SELECT @@VERSION to see what you're working with. If you're on 2016 or later, you're good to go.
  • For performance, avoid splitting in a WHERE clause. If you need to filter on a split value, consider storing the data in normalized form instead of splitting on the fly.
  • Use the ordinal parameter (2022+) when order matters. Without it, the order of rows is not guaranteed. If you need to know the position, use the ordinal.
  • Escape special characters in the XML method. If your data contains &, <, or >, you must escape them before building the XML.

Troubleshooting

  • "Invalid object name 'STRING_SPLIT'" – This means your SQL Server version is older than 2016. Use the recursive CTE or XML method instead. You can also check the compatibility level of your database: SELECT compatibility_level FROM sys.databases WHERE name = 'YourDB'. It should be 130 or higher for STRING_SPLIT.
  • Output column not found – If you wrote SELECT item FROM STRING_SPLIT(...) and get an error, remember the column is named value. Use SELECT value or alias it: SELECT value AS item.
  • Empty results when you expect data – Check if the input string is NULL. If so, STRING_SPLIT returns nothing. Use ISNULL(YourColumn, '') before passing it.
  • Order of rows is unpredictable – Without the ordinal parameter, STRING_SPLIT does not guarantee order. If order matters, upgrade to SQL Server 2022 or use a custom splitter that includes an index.
  • Special characters in XML method – If you get XML parsing errors, you likely have unescaped characters. Use REPLACE to escape &, <, and > before converting to XML.

Frequently Asked Questions

  1. Can I split a string into multiple columns instead of rows? Yes, you can use PARSENAME for up to 4 parts (e.g., PARSENAME('a.b.c.d', 2) returns 'c'), but it's limited and uses dot as delimiter. For more parts, consider using STRING_SPLIT with a pivot or use a custom function.
  2. How do I split by a tab character? Pass a tab as the delimiter: STRING_SPLIT(YourString, CHAR(9)). The CHAR(9) represents a tab.
  3. Does STRING_SPLIT handle quoted delimiters? No, it does not. It treats every occurrence of the delimiter as a split point, even if it's inside quotes. For CSV with quoted fields, you'll need a more advanced parser.
  4. Can I use STRING_SPLIT with a variable? Yes, you can pass any string expression, including a variable: DECLARE @list NVARCHAR(MAX) = 'a,b,c'; SELECT value FROM STRING_SPLIT(@list, ',');
  5. Is there a way to get the count of items? Yes, simply count the rows returned: SELECT COUNT(*) FROM STRING_SPLIT('a,b,c', ','); This returns 3.
  6. What if my delimiter is a multi-character string? STRING_SPLIT only accepts a single character. For multi-character delimiters, you'll need to use REPLACE to convert it to a single character first, or use a custom splitter.