我想重构以下语句,将where businessID = something
更改为一个语句,其中我提供了包含所有可能ID的字符串列表,例如where businessID in List
。现在,查询是在for循环中为每个Id执行的,我猜测它并不是真正的高效。我似乎无法找到有关如何在预准备语句中使用字符串列表作为参数的信息。
using (SqlConnection myConnection = new SqlConnection("Data Source=.\\SERVER;Initial Catalog=DB;Integrated Security=True;TrustServerCertificate=True;User Instance=False"))
using (SqlCommand myCommand = myConnection.CreateCommand())
{
myConnection.Open();
myCommand.CommandText = "SELECT BusinessName FROM Businessess WHERE BusinessID = @Param2";
myCommand.Parameters.AddWithValue("@Param2", myParam2);
using (SqlDataReader reader = myCommand.ExecuteReader())
{
if (reader.Read())
{
string businessName = reader.GetString(reader.GetOrdinal("BusinessName"));
MessageBox.Show(businessName);
}
else
{
MessageBox.Show(string.Format("Sorry, no business found with id = {0}", myParam2));
}
}
}
答案 0 :(得分:0)
通过在@Param2
"SELECT BusinessName FROM Businessess WHERE BusinessID IN(@Param2)";
IN 确定指定的值是否与子查询或列表中的任何值匹配。
由于@Prescott建议您从列表中创建逗号分隔字符串,您可以使用AddWithValue
myCommand.Parameters.AddWithValue("@Param2", String.Join(",", list));
如果不尝试使用存储过程而不是内联查询,请参阅比较Stored procedures vs. inline SQL。
答案 1 :(得分:0)
首先创建将列表转换为逗号分隔字符串
string commaSeparatedList = yourlist.Aggregate((a, x) => a + ", " + x);
将(=)更改为(In)并将@Param放在括号
之间myCommand.CommandText = "SELECT BusinessName FROM Businessess WHERE BusinessID IN ( @Param2 )";
将字符串(commaSeparatedList)作为参数添加到命令
myCommand.Parameters.AddWithValue("@Param2", commaSeparatedList );