public DataSet DataforTable(string fundID, string fromDate, string toDate)
{
string[] fundList = fundID.Split(',');
DataSet full = new DataSet();
DataTable ds = new DataTable();
full.Tables.Add(ds);
foreach (var fund in fundList)
{
using (strCon)
{
SqlCommand cmd = new SqlCommand("[dbo].[z_Formulas2]", strCon);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
cmd.Parameters.Add(new SqlParameter("@Fund_ID", fund));
cmd.Parameters.Add(new SqlParameter("@XFund_ID", ""));
cmd.Parameters.Add(new SqlParameter("@Start_Dated", fromDate));
cmd.Parameters.Add(new SqlParameter("End_Dated", toDate));
sda.Fill(ds);
}
}
return full;
}
我想为基金(数组)中的每个值运行我的 SP。我应该通过在 SP 中传递数组来在 SP 中执行此操作,还是应该在 C# 中执行此操作? 如果在 c# 中如何?我试过了,它运行第一个值,然后运行循环的第二个值,它给出错误:
The ConnectionString property has not been initialized
(下面给出代码)如果在 SP 中怎么办?
最佳答案
问题在于您放置 using (strCon)
的位置 - 因为它在循环中,然后在第一次之后 strCon
将被处理,然后您将不会'没有要使用的数据库的打开连接。
将 using
移动到 foreach
之上:
using (strCon)
{
foreach (var fund in fundList)
{
SqlCommand cmd = new SqlCommand("[dbo].[z_Formulas2]", strCon);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
cmd.Parameters.Add(new SqlParameter("@Fund_ID", fund));
cmd.Parameters.Add(new SqlParameter("@XFund_ID", ""));
cmd.Parameters.Add(new SqlParameter("@Start_Dated", fromDate));
cmd.Parameters.Add(new SqlParameter("End_Dated", toDate));
sda.Fill(ds);
}
}
当前方法的替代方法是将数组作为参数传递给 SP,然后将所有这些来回保存到数据库中。为此,请检查 this question
关于c# - 为数组中的每个值运行 SQL 存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38995092/