这是因为您试图将相同的参数重新添加到同一个 sqlcommand 对象。为了获得最佳性能,在开始 for 循环之前,打开连接并添加不带值的参数。然后,在您的 for 循环中,您所做的就是设置参数的值,然后执行该过程。无需在循环的每次迭代中重新创建参数本身,您只是白白浪费资源。试试这个:
string strCon = "Your Connection String Here";
using (SqlConnection conSQL = new SqlConnection(strCon))
{
conSQL.Open();
using (SqlCommand cmdSQL = new SqlCommand())
{
cmdSQL.CommandType = CommandType.StoredProcedure;
cmdSQL.CommandText = "The Name of Your Stored Procedure Here";
cmdSQL.Connection = conSQL;
// I'm just going to assume that the data type for the
// parameters is nvarchar and that both are input parameters...
// Just for demonstration purposes
cmdSQL.Parameters.Add("@In", SqlDbType.NVarChar, 50);
cmdSQL.Parameters.Add("@Out", SqlDbType.NVarChar, 50);
for (var j = 0; j <= weekDays.Length - 1; j += 1)
{
cmdSQL.Parameters("@In").Value = strIn;
cmdSQL.Parameters("@Out").Value = strOut;
// I'm not sure why in your code you put ExecuteReader here.
// You don't show that you're using the reader at all, rather
// it looks like you are actually just trying to execute the procedure without
// using any type of return parameter values or a reader.
// So I changed the code here to be what it should be if that is true.
cmdSQL.ExecuteNonQuery();
}
}
conSQL.Close();
}
我知道自从有人问这个问题已经有好几年了,但我认为仍然会有人搜索这个问题,也许会发现这个答案很有帮助。