Maybe I'm not doing something correctly, but I need to create a list of strings to filter some SQL SELECT query and all I can find are answers to escape a single parameter value only.
Given this array :
string[] domains = new string[] { "sec", "krn", "op", "ip" };
I need to create this query
SELECT * FROM user_domains WHERE name IN ("sec", "krn", "op", "ip")
Note : this is not a real query, but illustrate the point of this question.
A naïve solution would be to create a query as
SELECT * FROM user_domains WHERE name IN (@p1, @p2, @p3, @p4)
And executing the query with the params formatted as
Dictionary<string,string> inTerms = domains
.Select((t, i) => new { Key = "p" + i, Term = t })
.ToDictionary(item => item.Key, item => item.Term,
StringComparer.OrdinalIgnoreCase);
Is there another approach?
Update
Would it be just as easy and faster to perform a simple string comparison (aka index of) with a comma, or otherwise, separated string of terms?
Ex:
SELECT * FROM user_domains WHERE CHARINDEX(name, @terms) > 0