If you are using SQL Server 2008 or later, an alternative might be to use "table valued parameters". More info here : Arrays and Lists in SQL Server 2008 Using Table-Valued Parameters
`WHERE … IN @xs`, where @xs parameter is a value list: Supported by ADO.NET?
-
31-05-2022 - |
Question
I am trying to create a parameterised ADO.NET query with a WHERE … IN @xs
clause, where @xs
is a short list of possibly non-contiguous values, for instance (2, 3, 5, 8, 13)
. Can this be done? If so, how?
This won't work:
int[] xs = { 2, 3, 5, 8, 13 }; // I've also tried using a List<int> instead
var c = new System.Data.SqlClient.SqlCommand();
c.CommandText = "SELECT … FROM … WHERE … IN @xs";
c.Parameters.AddWithValue("@xs", xs); // throws ArgumentException due to `values`
Neither the System.Data.SqlDbType
enum nor the types in the System.Data.SqlTypes
namespace suggest that this scenario is supported. Must I revert to dynamic SQL (i.e. manually composing the final SQL CommandText
using string operations)?
Solution 2
OTHER TIPS
You will have to build the parameters one at a time:
int[] xs = { 2, 3, 5, 8, 13 };
var c = new SqlCommand();
var parameters = xs.Select((x, i) => string.Concat("@xs", i)).ToList();
for (var i = 0; i < xs.Count; i++)
{
c.Parameters.AddWithValue(parameters[i], xs[i]);
}
c.CommandText = string.Format(
"SELECT ... FROM ... WHERE ... IN ({0})",
string.Join(", ", parameters)
);
As you already found out: that is not supported.
int[] xs = { 2, 3, 5, 8, 13 };
var c = new System.Data.SqlClient.SqlCommand();
// this code assumes xs has always at least one item
var s = new StringBuilder("SELECT … FROM … WHERE … IN (@xs0");
c.Parameters.AddWithValue("@xs0", xs[0]);
for(int i = 1; i < xs.Length; i++)
{
s.AppendFormat(",@xs{0}", i);
c.Parameters.AddWithValue(String.Format("@xs{0}",i), xs[i]);
}
s.Append(")");
c.CommandText = s.ToString():
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow