让SqlDataAdapter和SqlCommand混淆

时间:2012-11-26 15:04:27

标签: c# sql-server ado.net

我有这种调用方法:

public string RunReportSteps(int _reportKey) {
    DataTable fStepsTable;
    fStepsTable =  GetStepsTable("xxx.console.pr_xxx");
    return (string)fStepsTable.Rows[1][3];
}

它调用这个私有方法:

private DataTable GetStepsTable(string procName) {
    var connectionString = ConfigurationManager.ConnectionStrings["xxx"].ConnectionString;
    using(var conn = new SqlConnection(connectionString))
    using(var adapt = new SqlDataAdapter())
    using(var cmd = new SqlCommand(procName, conn)) {

        conn.Open();

        SqlParameter p = new SqlParameter("@ReportKey", this.ReportKey);
        p.Direction = ParameterDirection.Input;
        cmd.Parameters.Add(p);
        adapt.SelectCommand = cmd;

        DataSet mySet = new DataSet();
        adapt.Fill(mySet);     //<<<<<<<<<<<<<<<<<<<errors here
        return mySet.Tables[0];
    }
}

为什么我收到以下错误消息?

  

过程或函数'pr_xxx'需要参数   '@ReportKey',未提供。

1 个答案:

答案 0 :(得分:5)

我假设procName是存储过程的名称。您尚未将SqlCommand的CommandType设置为StoredProcedure

using(var conn = new SqlConnection(connectionString))
using(var cmd = new SqlCommand(procName, conn))
using(var adapt = new SqlDataAdapter(cmd)) {
    cmd.CommandType = CommandType.StoredProcedure; // <<< this was missing

    SqlParameter p = new SqlParameter("@ReportKey", this.ReportKey);
    p.Direction = ParameterDirection.Input;
    cmd.Parameters.Add(p);

    DataTable table = new DataTable();
    adapt.Fill(table);     
    return table;
}