【问题标题】:Procedure or function ' ' expects parameter ' ' which is not supplied [duplicate]过程或函数“”需要未提供的参数“”[重复]
【发布时间】:2014-11-10 03:23:25
【问题描述】:

我遇到了一个看起来很“流行”的错误,这很烦人。但是,在我的情况下,我提供了预期的参数,它肯定有一个值,所以我很难过。这是我的代码:

public static DataTable MyDataTable(string pd, bool showAll)
{
    DataTable results = new DataTable("PD results");

    string Conn = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

    using (SqlConnection connection = new SqlConnection(Conn))
    {
        SqlCommand cmd = new SqlCommand("dbo.MyProcedure", connection);

        SqlParameter pdParam = new SqlParameter("@i_user", SqlDbType.VarChar);
        pdParam.Value = pd;
        cmd.Parameters.Add(pdParam);

        if (showAll) 
            cmd.Parameters.AddWithValue("@i_ShowALL", (int)1);
        else 
            cmd.Parameters.AddWithValue("@i_ShowALL", (int)0);

        SqlDataAdapter da = new SqlDataAdapter(cmd);

        try
        {
            da.Fill(results);
        }
        catch (Exception ex) 
        {
            string error = ex.Message;
        }
     }

     return results;
}

我已经单步执行了代码,错误出现在参数@i_user。但是,当我添加参数时,它有一个值,我在查看 SqlDataAdapter > SelectCommand >Parameters > Non-Public members > items > [0] {@i_user} > base > value 时确认了这一点。

尽管提供了带有varchar 值的参数,但我得到了错误

过程或函数“dbo.MyProcedure”需要未提供的参数“@i_user”

我做错了什么?

【问题讨论】:

  • 建议:添加cmd.CommandType = CommandType.StoredProcedure;
  • 正如 Dmity 所说,您并没有告诉 SqlCommand 您正在运行存储过程,因此它会将您的命令解释为不包含任何参数的简单 sql 字符串。
  • @DmitryBychenko - 解决了这个问题。我完全忘记添加了。愚蠢的错误。如果您将其添加为答案,我会接受。

标签: c# sql sql-server stored-procedures


【解决方案1】:

错误的原因是SqlCommand 类需要一个纯文本SQL。 分配存储过程名称时(在您的情况下为"dbo.MyProcedure")添加

  ... 
  // Do not forget to Dispose IDisposable instances
  using (SqlCommand cmd = new SqlCommand("dbo.MyProcedure", connection)) {
    // cmd.CommandText is a stored procedure name, not a plain text SQL 
    cmd.CommandType = CommandType.StoredProcedure;
     ...
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-05
    • 2013-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多