Home >Database >Mysql Tutorial >How to Efficiently Parse Comma-Separated Strings for SQL IN Clauses?
Handling Comma-Separated Strings in SQL Queries
Many database operations require input parameters as lists. When these lists are provided as comma-separated strings, converting them to a SQL-compatible format is crucial.
The Challenge:
Consider a stored procedure receiving a comma-separated string like this:
<code class="language-sql">DECLARE @Account AS VARCHAR(200) SET @Account = 'SA,A'</code>
The goal is to transform this string into a usable SQL IN
clause:
<code class="language-sql">WHERE Account IN ('SA', 'A')</code>
A High-Performance Solution:
A user-defined function offers the most efficient approach. This function splits the comma-separated string into a table:
<code class="language-sql">CREATE function [dbo].[f_split] ( @param nvarchar(max), @delimiter char(1) ) returns @t table (val nvarchar(max), seq int) as begin set @param += @delimiter ;with a as ( select cast(1 as bigint) f, charindex(@delimiter, @param) t, 1 seq union all select t + 1, charindex(@delimiter, @param, t + 1), seq + 1 from a where charindex(@delimiter, @param, t + 1) > 0 ) insert @t select substring(@param, f, t - f), seq from a option (maxrecursion 0) return end</code>
This function is then used within the SQL query:
<code class="language-sql">SELECT * FROM yourtable WHERE account in (SELECT val FROM dbo.f_split(@account, ','))</code>
Why This Method Is Superior:
Compared to alternatives like XML parsing, this function provides:
The above is the detailed content of How to Efficiently Parse Comma-Separated Strings for SQL IN Clauses?. For more information, please follow other related articles on the PHP Chinese website!