2010-09-28 23 views
1

現在這是我的更新記錄代碼。Int結果不使用Cmd.ExecuteScalar PRoblem增加?

數據訪問:

public int UpdateBatch(FillinEntity fin) 
    { 
     int result = 0; 
     using (SqlConnection conn = new SqlConnection(connStr)) 
     { 
      conn.Open(); 

      using (SqlCommand dCmd = new SqlCommand("UpdatebyBatch", conn)) 
      { 
       dCmd.CommandType = CommandType.StoredProcedure; 
       try 
       { 
        dCmd.Parameters.AddWithValue("@Batch", fin.Batch); 
        dCmd.Parameters.Add("@Date", SqlDbType.DateTime).Value = DateTime.Now.ToString(); 
        dCmd.Parameters.AddWithValue("@User", fin.ModifiedBy); 

        result = Convert.ToInt32(dCmd.ExecuteScalar()); 

        return result; 

       } 
       catch (SqlException ee) 
       { 
        throw ee; 
       } 
       finally 
       { 
        if (conn.State == ConnectionState.Open) conn.Close(); 

       } 
      } 
     } 
    } 

商業邏輯:

public int UpdateBatch(FillinEntity fin) 
    { 
     DAL pDAL = new DAL(); 
     try 
     { 
      return pDAL.UpdateBatch(fin); 
     } 
     catch 
     { 
      throw; 
     } 
     finally 
     { 
      pDAL = null; 
     } 
    } 

UI:

  FillinEntity fin = new FillinEntity(); 
     BAL pBAL = new BAL(); 
     try 
     { 
      fin.Batch = txtBACTHCODE.Text.Trim(); 
      fin.ModifiedBy = lblUser.Text; 

      int result = pBAL.UpdateBatch(fin); 
      if (result > 0) 
      { 
       MessageBox.Show("Make Sure Batch is All Kitted!"); 

      } 
      else 
      { 
       MessageBox.Show("Record Updated Successfully."); 
      } 

SQL:

UPDATE dbo.FG_FILLIN SET 
    Status='SHIPPED' 
    ,[email protected] 
    ,[email protected] 
WHERE Batch = @Batch and (Status='KITTED') 

我的問題是它總是返回0結果,所以我的消息框總是提示成功,即使我的狀態不匹配。

謝謝!

回答

2

您的存儲過程未返回ExecuteScalar可以使用的值。您可以使用ExecuteNonQuery method來返回受影響記錄的數量。

result = dCmd.ExecuteNonQuery(); 
1

爲了使ExecuteScalar返回一個值,必須返回一個值。你可以修改你的SQL,如下所示:

UPDATE dbo.FG_FILLIN SET 
    Status='SHIPPED' 
    ,[email protected] 
    ,[email protected] 
WHERE Batch = @Batch and (Status='KITTED') 

SELECT @@ROWCOUNT 

或者你可以改用ExecuteNonQuery方法。