Suppose you need to write a query that uses IN clause but you don't want to create a Stored Procedure. Using inline query is a possibility but not recommended. The only viable option is to use parameterized query. But it is a little tricky for IN clause.
Here is one work around you can apply.
string sql = "SELECT * FROM dbo.TestTable A WHERE A.Name1 IN (__Keys__)";
List values = new List() { "Name1", "Name2" };
string parameterTemplate = "@name{0}";
List parameters = new List();
using (var conn = new SqlConnection(@"connString"))
{
using (var cmd = new SqlCommand())
{
cmd.CommandType = System.Data.CommandType.Text;
int i = 0;
foreach(string val in values)
{
string paramName = string.Format(parameterTemplate, i);
parameters.Add(paramName);
cmd.Parameters.Add(new SqlParameter(paramName, values[i]));
i++;
}
sql = sql.Replace("__Keys__", string.Join(",", parameters));
cmd.CommandText = sql;
cmd.Connection = conn;
conn.Open();
using (var reader = cmd.ExecuteReader())
{
while(reader.Read())
{
Console.WriteLine(string.Format("{0},{1},{2}", reader[0], reader[1], reader[2]));
}
}
}
}
Hope it helps.
Here is one work around you can apply.
string sql = "SELECT * FROM dbo.TestTable A WHERE A.Name1 IN (__Keys__)";
List
string parameterTemplate = "@name{0}";
List
using (var conn = new SqlConnection(@"connString"))
{
using (var cmd = new SqlCommand())
{
cmd.CommandType = System.Data.CommandType.Text;
int i = 0;
foreach(string val in values)
{
string paramName = string.Format(parameterTemplate, i);
parameters.Add(paramName);
cmd.Parameters.Add(new SqlParameter(paramName, values[i]));
i++;
}
sql = sql.Replace("__Keys__", string.Join(",", parameters));
cmd.CommandText = sql;
cmd.Connection = conn;
conn.Open();
using (var reader = cmd.ExecuteReader())
{
while(reader.Read())
{
Console.WriteLine(string.Format("{0},{1},{2}", reader[0], reader[1], reader[2]));
}
}
}
}
Hope it helps.