How to execute stored procedure multiple times in C#

南楼画角 提交于 2019-11-30 20:36:53
Kyle W
SqlConnection conn = new SqlConnection(connString);
conn.Open();
SqlCommand cmd = new SqlCommand("insertINOUT", conn);
cmd.CommandType = CommandType.StoredProcedure;

for (int j = 0; j < weekDays.Length; j++)
{
    **cmd.Parameters.Clear();**
    cmd.Parameters.Add(new SqlParameter("@UserName", user));
    cmd.Parameters.Add(new SqlParameter("@In", in));
    cmd.Parameters.Add(new SqlParameter("@Out", out));
    cmd.ExecuteReader();
}
conn.Close();

(You have to clear the parameters each iteration.)

Another alternative, you could change the scope of the SqlCommand so that it is recreated each time.

SqlConnection conn = new SqlConnection(connString);
conn.Open();

for (int j = 0; j < weekDays.Length; j++)
{
    SqlCommand cmd = new SqlCommand("insertINOUT", conn);
    cmd.CommandType = CommandType.StoredProcedure;

    cmd.Parameters.Add(new SqlParameter("@UserName", user));
    cmd.Parameters.Add(new SqlParameter("@In", in));
    cmd.Parameters.Add(new SqlParameter("@Out", out));
    cmd.ExecuteReader();
}
conn.Close();

Seems a bit wasteful, but there are some libraries that work this way (the Enterprise Library DAAB comes to mind).

HABO
using (SqlConnection conn ... )
{
    SqlCommand cmd = ...
    ...
    // Set up the parameter list.
    //   You can use   .AddWithValue   here to add values that don't change in the loop.
    cmd.Parameters.Add("@Username", SqlDbType.VarChar);
    ...
    for (...)
    {
        // Load one set of loopy values.
        cmd.Parameters["@UserId"].Value = user;
        ...
    }
}

The reason you are getting that error is because the for loop is re-adding the parameter multiple times:

cmd.Parameters.Add(new SqlParameter("@In", in));
cmd.Parameters.Add(new SqlParameter("@Out", out));

The proper way to do this is either clear the Parameters collection at the last line of the foor loop or simply check if the parameter already exists and set its value instead of doing Parameters.Add

SqlConnection conn = new SqlConnection(connString);
conn.Open();
SqlCommand cmd = new SqlCommand("insertINOUT", conn);

    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add(new SqlParameter("@UserName", user));
    for (int j = 0; j < weekDays.Length; j++)
    {


        cmd.Parameters.Add(new SqlParameter("@In"+j, in));
        cmd.Parameters.Add(new SqlParameter("@Out"+j, out));
        cmd.ExecuteReader();
    }
    conn.Close();
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!