繁体   English   中英

如何使用DataAdapter通过可变参数在C#中调用存储过程

[英]How to use DataAdapter to call a stored procedure in C# with variable parameters

我打电话在C#下面的代码,以填补一个给定存储过程“sp1_name”一个DataAdapter。 问题是我想用不同的参数调用不同的存储过程。 (所有SP都执行SELECT)假设我的存储过程名称为“ SP_SOMESP” ,那么一切正常。

假设我的存储过程名称为“ SP_SOMESP @ Month = 10,@Year = 2010” ,则它不起作用。 它将引发找不到该存储过程的异常。

有什么办法吗?

谢谢!

//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);
                }

            }
}

您必须以编程方式添加参数,请参见SqlCommand.Parameters

就像

cmd.Parameters.AddWithValue("@Month", 10);
cmd.Parameters.AddWithValue("@Year", 2010);

这将在命令声明之后和执行之前。

如果发现需要删除数据类型,请尝试这种方式

cmd.Parameters.Add("@Month", SqlDbType.Int).Value = 10;

首要问题:
存储过程中的参数不应与其名称一起包含
第二期:
在存储过程的名称中使用空格不是一个好习惯。
对于后面的代码

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
    }
}

检查一下

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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM