如何在C#中多次执行存储过程 [英] How to execute stored procedure multiple times in C#

查看:122
本文介绍了如何在C#中多次执行存储过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个时间表应用程序,用户可以在其中输入/输入一周中不同日期的时间.表单每天处理输入/输出,将它们作为参数填充到存储过程中,并将其添加到数据库中.我将如何最有效地完成此任务?我没有访问数据库的权限,只有存储过程的权限.

I have a time sheet app where users enter their time in/out for different days of the week. The form processes the in/out from each day, stuff them as parameters into a stored procedure and add them to the database. How would I accomplish this most efficiently? I don't have access to the DB, just the stored procedures.

这是背后的空白代码,我删除了一些不必要的代码.

This is the bare code behind, I've stripped out some unnecessary codes.

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", in));
    cmd.Parameters.Add(new SqlParameter("@Out", out));
    cmd.ExecuteReader();
}
conn.Close();

如果只有1天的进/出代码,则此代码有效.如果用户填写了多天,我将收到此错误消息:多次提供了参数'@In'.

The code works if there's only 1 day of in/out. If the users fill out multiple days, I'll get this error: Parameter '@In' was supplied multiple times.

感谢您的帮助.

推荐答案

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.)

这篇关于如何在C#中多次执行存储过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆