【问题标题】:Update Command with stored procedure使用存储过程更新命令
【发布时间】:2013-11-27 10:59:44
【问题描述】:

我有一个更新查询(存储过程),当我执行它时它在 SQL Server 中正常工作。

CREATE PROCEDURE updatestudenthws(@stdid nvarchar(50),@hwid int, @grade float)
AS
UPDATE Table_Exercise_Answer 
SET
ExAns_Grade = @grade
WHERE ExAns_Exercise = @hwid AND ExAns_Student = @stdid

但是当我运行程序时,它对我的​​表没有任何影响,而且我也没有任何错误。

     con.Open();
        SqlCommand cmd = new SqlCommand("updatestudenthws", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("@hwid", SqlDbType.VarChar);
        cmd.Parameters.Add("@stdid", SqlDbType.VarChar);
        cmd.Parameters.Add("@grade", SqlDbType.VarChar);
        cmd.Parameters["@hwid"].Value = hwid;
        cmd.Parameters["@stdid"].Value = studentid;
        cmd.Parameters["@grade"].Value = grade;

        cmd.ExecuteNonQuery(); 
     con.Close();

我的错误是什么? 我应该如何完成这项工作?

【问题讨论】:

  • 您是否检查过您是否传递了所需的 hwid 和 stdid 参数? Myabe 的 stdid 是否超过 50 个字符?
  • 为什么您在 sp 中将 @hwid 定义为 int 而将参数添加为 SqlDbType.VarChar
  • 我怀疑 where 子句中的参数,你在调试时检查过它们的值吗?
  • 你的hwid、studentid、grade有值吗?
  • 尝试更改 cmd.Parameters.Add("@hwid", SqlDbType.Int);和 cmd.Parameters.Add("@grade", SqlDbType.Float);

标签: c# sql sql-server winforms


【解决方案1】:

使用AddWithValue(),因此您不必提供类型,这让您犯了将varchar 传递给int 参数的错误。

 con.Open();
    SqlCommand cmd = new SqlCommand("updatestudenthws", con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@hwid", hwid);
    cmd.Parameters.AddWithValue("@stdid", studentid);
    cmd.Parameters.AddWithValue("@grade", grade);
    cmd.ExecuteNonQuery(); 
 con.Close();

【讨论】:

    【解决方案2】:

    您为存储过程定义参数的 ADO.NET 代码是错误的,因为您没有使用正确的数据类型定义参数。

    您的存储过程定义:

    • @stdid nvarchar(50) --> 但您将其定义为 varchar
    • @hwid int --> 但您将其定义为 varchar
    • @grade float --> 但您将其定义为 varchar

    您需要将代码更改为:

    SqlCommand cmd = new SqlCommand("updatestudenthws", con);
    cmd.CommandType = CommandType.StoredProcedure;
    
    cmd.Parameters.Add("@hwid", SqlDbType.Int);   // this needs to be SqlDbType.Int 
    cmd.Parameters.Add("@stdid", SqlDbType.NVarChar, 50);  // this should be SqlDbType.NVarChar and specify its proper length
    cmd.Parameters.Add("@grade", SqlDbType.Float);  // this needs to be SqlDbType.Float
    

    【讨论】:

      【解决方案3】:

      当你使用 AddWithValue() 时,你不必像 varchar 一样向 int 参数提供类型传递。

       con.Open();
              SqlCommand cmd = new SqlCommand("updatestudenthws", con);
              cmd.CommandType = CommandType.StoredProcedure;
              cmd.Parameters.AddWithValue("@hwid", hwid);
              cmd.Parameters.AddWithValue("@stdid", studentid);
              cmd.Parameters.AddWithValue("@grade", grade);
              cmd.ExecuteNonQuery(); 
           con.Close();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多