Split Delimited Text into Ordered SQL Server Rows
STRING_SPLIT turns a delimited value into a rowset without maintaining a hand-written loop. On SQL Server 2022 and later, its optional ordinal output also lets you reconstruct the original token order explicitly.
Run each code example below as a separate batch. Each splitting example declares its own input variable.
Check Availability
SELECT SERVERPROPERTY('ProductVersion') AS ProductVersion;
SELECT name, compatibility_level
FROM sys.databases
WHERE database_id = DB_ID();
The examples with a third argument target SQL Server 2022 or later. Use a database compatibility level of at least 130 for the standard STRING_SPLIT availability requirement. Review a compatibility-level change as a database-wide change rather than raising it blindly for one query.
Split and Preserve Positions
DECLARE @Input nvarchar(100) = N'red, blue,,green';
SELECT ordinal, TRIM(value) AS Token
FROM STRING_SPLIT(@Input, N',', 1)
ORDER BY ordinal;
Expect red, blue, an empty token and green at positions 1 through 4. The 1 enables a one-based ordinal column. It does not by itself sort the rows, so keep ORDER BY ordinal when order matters.
Discard Empty Tokens Intentionally
DECLARE @Input nvarchar(100) = N'red, blue,,green';
SELECT ordinal, TRIM(value) AS Token
FROM STRING_SPLIT(@Input, N',', 1)
WHERE TRIM(value) <> N''
ORDER BY ordinal;
This returns positions 1, 2 and 4. Retaining those positions makes it clear that a token was removed. If blanks carry meaning in your format, do not filter them out.
Validate Numeric Tokens before Using Them
DECLARE @Input nvarchar(100) = N'12, 18, invalid';
SELECT ordinal, TRIM(value) AS Token,
TRY_CONVERT(int, TRIM(value)) AS ParsedId
FROM STRING_SPLIT(@Input, N',', 1)
ORDER BY ordinal;
The final row has a null ParsedId. Decide whether that should reject the input or be reported to the caller before using the result to select or modify records. A split list should not become concatenated dynamic SQL.
Respect the Format Boundary
The separator is one character. This function is not a parser for quoted CSV, escaped delimiters, multi-character separators or arbitrary structured text. SQL Server 2016–2019 support the two-argument form but do not expose the ordinal column. Do not invent order by numbering an unordered result afterward.
For a format that needs multi-character delimiters or quoted fields, parse it with a suitable format-aware component or use a structured input contract. Keep the legacy custom splitter only where its different semantics are an intentional compatibility requirement.
Microsoft References
Author: Herman Schoenfeld