2011-09-19 50 views
2

運行Enterprise Library 5.0的示例,當我使用ExecuteNonQuery運行更新存儲過程時,它返回2.更新基於ProductID,表的主鍵(是,我查過了,而且是獨一無二的)。ExecuteNonQuery在僅更新1條記錄時返回值爲2

下面是簡單的存儲過程:

ALTER PROCEDURE [dbo].[UpdateProductsTable] 
    @ProductID int, 
    @ProductName varchar(50) = NULL, 
    @CategoryID int = NULL, 
    @UnitPrice money = NULL 
AS 
BEGIN 
    UPDATE Products 
    SET 
     ProductName = @ProductName, 
     CategoryID = @CategoryID, 
     UnitPrice = @UnitPrice 
    WHERE ProductID = @ProductID 
END 

執行該SP在SSMS顯示在查詢結果窗口的右下角「1行」,以及0網格中的一個返回值。點擊郵件標籤顯示

(1 row(s) affected) 

(1 row(s) affected) 

(1 row(s) affected) 

不知道爲什麼我在這裏看到這3次,但我不認爲這是問題。

這裏是代碼調用SP:

public static void Exec_Update_Query() 
     //updates a column of a single row, checks that the update succeeded, and then update it again to return it to the original value 
     { 
      string oldName = "Chai"; 
      string newName = "Chai Tea"; 

      SqlDatabase defaultDB = EnterpriseLibraryContainer.Current.GetInstance<Database>() as SqlDatabase; 

      // Create command to execute the stored procedure and add the parameters. 
      DbCommand cmd = defaultDB.GetStoredProcCommand("UpdateProductsTable"); 
      defaultDB.AddInParameter(cmd, "ProductID", DbType.Int32, 1); 
      defaultDB.AddInParameter(cmd, "ProductName", DbType.String, newName); 
      defaultDB.AddInParameter(cmd, "CategoryID", DbType.Int32, 1); 
      defaultDB.AddInParameter(cmd, "UnitPrice", DbType.Currency, 18); 

      // Execute the query and check if one row was updated. 
      int i = defaultDB.ExecuteNonQuery(cmd); 
      if (i == 1) 
      { 
       // Update succeeded. 
      } 
      else 
      { 
       Console.WriteLine("ERROR: Could not update just one row."); 
      } 

      // Change the value of the second parameter 
      defaultDB.SetParameterValue(cmd, "ProductName", oldName); 

      // Execute query and check if one row was updated 
      if (defaultDB.ExecuteNonQuery(cmd) == 1) 
      { 
       // Update succeeded. 
      } 
      else 
      { 
       Console.WriteLine("ERROR: Could not update just one row."); 
      } 
     } 

我使用INT I,閱覽從方法的返回值,並將其返回2.任何想法,爲什麼這會是什麼?這是針對SQL 2005運行的VS2010中的Enterprise Libarary 5.0。非常簡單但很令人困惑。

回答

5

如果我沒有記錯,任何由於命令而觸發的觸發器的結果也將包含在返回的行數中。很可能,這是你的問題。

編輯:文檔

MSDN SqlCommand.ExecuteNonQuery

當觸發上被插入或更新一個表中存在,則返回值包括受插入或更新操作和兩者的行數受觸發器或觸發器影響的行數。

+0

Thx奧斯汀,我不知道!這正是它 - 設置LastModified字段的更新觸發器。現在驗證值爲2 - LOL –

+0

是否有避免受觸發影響的行,並只獲取受實際dml操作影響的行? –

+0

@ girishgupta211 - 我不這麼認爲,但這是一個很好的問題,問社區,我們可以從這裏鏈接到它。 –