[英]output clause returns value but executescalar returns null in c#
我需要獲取更新行的第一列值。 但是,當我運行 query Update ClaimDetails set sStatus='False' OUTPUT inserted.slno as Slno where inVoiceNo='******' and sStatus='True'
在 Management Studio 中,它返回正確的值。 但是當我嘗試使用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
ExecuteScalar
返回null
的唯一時間是沒有返回任何行。 如果返回一個排和值是null
,那么DbNull.Value
而是返回。
所以:沒有匹配的行。 檢查@inVoiceNo
是什么,以及它是否存在於您正在運行的表中。 混淆的常見原因:
代碼兩次執行相同的UPDATE
命令,一次使用 ExecuteNonQuery(它丟棄標量結果並返回受影響的行數),再次使用 ExecuteScalar。 由於WHERE
子句中的硬編碼“True”,當提供的sStatus
值為“False”時,同一命令的第二次調用將永遠不會更新行。 在這種情況下,標量結果將始終為null
。
我認為您可以重構如下代碼以獲得所需的結果。
object a = cmd.ExecuteScalar();
if (a != null)
{
isupdated = true;
modified = Convert.ToInt32(a);
}
如果有人想要更新的實際記錄數而不僅僅是處理空值,在我們的數據庫開發人員設置的存儲過程中返回@@ROWCOUNT [typo] 而不是SELECT @@ROWCOUNT
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.