输出子句返回值,但执行标量在 C# 中返回 null




我需要获取更新行的第一列值。但是当我运行查询Update ClaimDetails set sStatus='False' OUTPUT inserted.slno as Slno where inVoiceNo='******' and sStatus='True'
在管理工作室中,它返回正确的值。但是当我尝试使用 Executescalar() 获取值时,它会返回 null

我的代码:

 bool isupdated = false;
        int modified=0;
        try
        {
            string updateqry = "Update ClaimDetails set sStatus=@sStatus OUTPUT inserted.slno as Slno where inVoiceNo=@inVoiceNo and sStatus='True'";
            SqlCommand cmd = new SqlCommand(updateqry, con);
            cmd.Parameters.AddWithValue("@sStatus", sStatus);
            cmd.Parameters.AddWithValue("@inVoiceNo", inVoiceNo);
            connect();
            if (cmd.ExecuteNonQuery() > 0)
            {
                isupdated = true;
                 //modified = (int)cmd.ExecuteScalar();
                object a = cmd.ExecuteScalar();
                if (a != null)
                    modified = Convert.ToInt32(a);
            }
        }
        catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); }
        finally { disconnect(); }
        return modified;

当我使用modified = (int)cmd.ExecuteScalar();时,它给了我一个异常错误,所以我使用了object

代码执行相同的UPDATE命令两次,一次使用 ExecuteNonQuery(丢弃标量结果并返回受影响的行计数(,另一次使用 ExecuteScalar。由于 WHERE 子句中的硬编码"True",当提供的sStatus值为"False"时,同一命令的第二次调用将永远不会更新行。 在这种情况下,标量结果将始终null

我认为您可以按如下方式重构代码以获得所需的结果。

object a = cmd.ExecuteScalar();
if (a != null)
{
    isupdated = true;
    modified = Convert.ToInt32(a);
}

ExecuteScalar返回null的唯一时间是不返回任何行。如果返回一行并且值null ,则返回DbNull.Value

所以:没有行匹配。检查什么是@inVoiceNo,以及它是否存在于您正在运行的表中。混淆的常见原因:

  • 数据库中区分大小写
  • Unicode vs ASCII/代码页值
  • 查尔 vs 瓦尔查尔,恩查尔
  • vs 恩瓦尔查尔
  • 针对错误的数据运行

如果有人想要更新的实际记录数而不仅仅是处理空值,,在存储过程中,我们的数据库开发人员设置返回@@ROWCOUNT [拼写错误] 而不是 SELECT @@ROWCOUNT

最新更新