程序或功能' '期望参数' '没有提供

时间:2014-09-16 11:35:33

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

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

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>参数>非公开会员>项目> [0] {@ i_user}>基数>值。

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

  

程序或函数'dbo.MyProcedure'需要参数'@i_user'未提供

我做错了什么?

1 个答案:

答案 0 :(得分:3)

错误的原因是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;
     ...
  }