3

Enterprise Library 5.0の例を実行し、ExecuteNonQueryを使用して更新sprocを実行すると、2が返されます。更新は、テーブルの主キーであるProductIDに基づいています(はい、確認しましたが、一意です)。

単純なsprocは次のとおりです。

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

SSMSでこのspを実行すると、クエリ結果ウィンドウの右下隅に「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が返されます。これがなぜであるかについてのアイデアはありますか?これは、SQL2005に対して実行されているVS2010のEnterpriseLibarary 5.0です。非常に単純ですが、複雑です。

4

1 に答える 1

5

正しく思い出せば、コマンドの結果として起動したトリガーの結果も、返される行数に含まれます。ほとんどの場合、これはあなたの問題です。

編集:ドキュメント

MSDN SqlCommand.ExecuteNonQueryから:

挿入または更新されるテーブルにトリガーが存在する場合、戻り値には、挿入または更新操作の両方の影響を受ける行数と、1つまたは複数のトリガーの影響を受ける行数が含まれます。

于 2011-09-19T21:25:28.373 に答える