2016-08-12 67 views
0

我試圖執行一個存儲過程並打印輸出,但是當我運行下面的代碼時,我得到錯誤,如「過程或函數'SPInsertLocal'期望參數'@RES',它沒有提供。「過程或函數期望沒有提供的參數。」

private void InsertPdtLocal(string code, string PON,string Qty) 
     { 
      string str = Properties.Settings.Default.conLocal; 
      SqlConnection con = new SqlConnection(str); 
      SqlCommand cmd = new SqlCommand("Execute SPInsertLocal @PON,@TCode,@Qty,@Type", con); 
      try 
      { 
       con.Open(); 
       cmd.CommandTimeout = 150; 
       cmd.Parameters.AddWithValue("@PON", PON); 
       cmd.Parameters.AddWithValue("@Qty", Qty); 
       cmd.Parameters.AddWithValue("@TCode", code); 
       cmd.Parameters.AddWithValue("@Type", Globals.s_type); 
       SqlParameter output = new SqlParameter("@RES", SqlDbType.Int); 
       output.Direction = ParameterDirection.Output; 
       cmd.Parameters.Add(output); 
       cmd.ExecuteNonQuery(); 
       con.Close(); 
       int id = Convert.ToInt32(output.Value); 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message); 
      } 

我在做什麼錯在這裏?

+4

您的SQLCommand不包含@RES。你也可以使用新的SqlCommand(「SPInsertLocal」,con),然後指定CommandType = CommandType.StoredProcedure; –

+1

您應該使用using語句以及SQLCommand實現IDisposible –

回答

1
SqlCommand cmd = new SqlCommand("Execute SPInsertLocal @PON,@TCode,@Qty,@Type,@RES", con); 

我並沒有傳遞參數,解決了該問題

0

您可以重構代碼如下,其中using語句用於關閉連接的自動管理,避免硬編碼在C#代碼執行聲明,是不好的做法

private void InsertPdtLocal(string code, string PON,string Qty) 
     { 
      string str = Properties.Settings.Default.conLocal; 
      try 
      { 

      using (SqlConnection con = new SqlConnection(str)) 
      { 
       using (SqlCommand cmd = con.CreateCommand()) 
       { 
        cmd.Parameters.AddWithValue("@PON", PON); 
        cmd.Parameters.AddWithValue("@Qty", Qty); 
        cmd.Parameters.AddWithValue("@TCode", code); 
        cmd.Parameters.AddWithValue("@Type", Globals.s_type); 
        var output = cmd.Parameters.Add("@RES" , SqlDbType.Int); 
        output.Direction = ParameterDirection.Output; 
        cmd.ExecuteNonQuery(); 
        int id = Convert.ToInt32(output.Value); 
       } 
      } 

      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message); 
      } 
     } 
相關問題