2012-11-26 19 views
1

我有了這個調用方法:獲取的SqlDataAdapter和SqlCommand的困惑

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'。

+3

我不知道這是否是問題的根源,但你不應該指定要使用存儲過程? –

回答

5

我假設procName是存儲過程的名稱。您還沒有設置的SqlCommand的CommandTypeStoredProcedure

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; 
} 
+0

謝謝... +我沒有真正需要數據集; +我弄錯了適配器和sqlcommand的順序! – whytheq

+1

@whytheq:另外請注意,您不需要手動打開連接,因爲DataAdapter會在['Fill']中爲您執行此操作(http://msdn.microsoft.com/zh- cn/library/905keexk.aspx)。 –

+0

謝謝;蒂姆,你的幫助總是受到讚賞 – whytheq