2016-08-12 71 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); 
      } 
     } 
相关问题