In this post, we discuss best practices for split comma delimited string SQL Server. Many a time we come across a scenario where we pass a comma or any other character delimited string to stored procedure and in a stored procedure, we want to fetch data from other tables based on this delimited string. We can’t use this delimited string or split comma delimited string SQL directly in the clause as SQL treats it as one string. So, the solution for this is to get a table by splitting the delimited string by the delimiter character and then join this resultant table data with other table columns.

 

In SQL Server we have a mechanism where we can take a table as an input parameter from the application code. So if you like to pass a table from your code with multiple rows instead of passing a delimited string to stored procedure and splitting it in SP, then you may like to read the article Table Type Parameters in SQL Server. But I would prefer passing the comma-delimited string to the stored procedure and splitting it in the SP.

 

In SQL Server we have multiple approaches to achieve this. This article lists a couple of them. Please let me know which one you use and if you use some other approach let me know so that we can help the SQL Server developer community.

 

APPROACH 1: SQL Server 2016 STRING_SPLIT function

STRING_SPLIT is one of the new built-in table-valued functions introduced in SQL Server 2016. This table valued function splits the input string by the specified character separator and returns the output as a table. The below example shows how we can use the STRING_SPLIT function to splits the comma-separated string.

 

APPROACH 2: Using While Loop and SQL String Functions

We can create a table-valued function like the below which is using WHILE loop and SQL String functions like CHARINDEX and SUBSTRING to split the string. This should work in all the versions of SQL Server.

The below example shows how we can use the above function to split the comma-delimited string

 

APPROACH 3: Using XML

We can create a table-valued function like the below which is using the SQL XML feature to split the string.

The below example shows how we can use the above function to split the comma-delimited string

Best practice for split comma delimited string SQL Server

Leave a Comment