如何使用DataAdapter调用C#中具有可变参数的存储过程
我用C语言调用以下代码,用给定的存储过程“sp1#u name”填充dataAdapter。问题是我想用不同的参数调用不同的存储过程(所有SP都进行选择) 假设我的存储过程名为“SP_SOMESP”,那么一切正常 假设我的存储过程名为“SP_SOMESP@Month=10,@Year=2010”,那么它就不工作了。它抛出一个找不到此存储过程的异常 有什么解决办法吗 谢谢如何使用DataAdapter调用C#中具有可变参数的存储过程,c#,sql,sql-server,stored-procedures,connection,C#,Sql,Sql Server,Stored Procedures,Connection,我用C语言调用以下代码,用给定的存储过程“sp1#u name”填充dataAdapter。问题是我想用不同的参数调用不同的存储过程(所有SP都进行选择) 假设我的存储过程名为“SP_SOMESP”,那么一切正常 假设我的存储过程名为“SP_SOMESP@Month=10,@Year=2010”,那么它就不工作了。它抛出一个找不到此存储过程的异常 有什么解决办法吗 谢谢 //First Connection - SP1 using (SqlConnection con = new SqlConn
//First Connection - SP1
using (SqlConnection con = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand(sp1_name, con)) //sp1_name = NAME + PARAMETERS
{
cmd.CommandTimeout = 3600;
cmd.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd))
{
dataAdapter.Fill(results2);
}
}
}
必须以编程方式添加参数,请参见 大概是
cmd.Parameters.AddWithValue("@Month", 10);
cmd.Parameters.AddWithValue("@Year", 2010);
这将是在命令声明之后和执行之前
如果您发现需要删除数据类型,那么可以这样尝试
cmd.Parameters.Add("@Month", SqlDbType.Int).Value = 10;
看看这个
using (SQLCommand cmd = new SQLCommand())
{
cmd.CommandText = "SP_SOMESP";
cmd.Parameters.Add("@Month", 10);
cmd.Parameters.Add("@Year", 2010);
cmd.CommandTimeout = 3600;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
}
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd))
{
dataAdapter.SelectCommand = cmd;
dataAdapter.Fill(results2);
}
第一期:
存储过程中的参数不应与其名称一起包含
第二期:
在存储过程的名称中使用空格不是一种好做法。
对于代码隐藏
using(SqlConnection con = new SqlConnection("Your Connection String Here"))
{
SqlCommand cmd = new SqlCommand("sp_SomeName", con);
cmd.CommandType = CommandType.StoredProcedure;
//the 2 codes after this comment is where you assign value to the parameters you
//have on your stored procedure from SQL
cmd.Parameters.Add("@MONTH", SqlDbType.VarChar).Value = "someValue";
cmd.Parameters.Add("@YEAR", SqlDbType.VarChar).Value = "SomeYear";
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataSet ds = new SqlDataSet();
da.Fill(ds); //this is where you put values you get from the Select command to a
//dataset named ds, reason for this is for you to fetch the value from DB to code behind
foreach(DataRow dr in ds.Tables[0].Rows) // this is where you run through the dataset and get values you want from it.
{
someTextBox.Text = dr["Month"].ToString(); //you should probably know this code
}
}
您确实应该始终声明数据类型。它消除了.net出错的可能性。没错,这是一个很好的做法。关于那篇文章的一条评论提到,在使用存储过程时,这并不是什么大问题,因为存储过程的参数已经声明为特定类型。同意。我个人更喜欢总是指定数据类型和大小。您不必记录为什么这次使用AddWithValue,也不必记录那次使用AddWithValue的原因。:)你说得对,只有你说得更具体一点才有帮助。