JM.*_*JM. 2 enterprise-library executenonquery c#-4.0
运行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
Run Code Online (Sandbox Code Playgroud)
在SSMS中执行此sp在查询结果窗口的右下角显示"1行",并在网格中返回0.单击消息选项卡显示
(1 row(s) affected)
(1 row(s) affected)
(1 row(s) affected)
Run Code Online (Sandbox Code Playgroud)
不知道为什么我在这里看到这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.");
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用int i来查看方法的返回值,它返回2.任何想法为什么会这样?这是VS2010中针对SQL 2005运行的Enterprise Libarary 5.0.非常简单但令人困惑.
如果我没记错的话,由于命令而触发的任何触发器的结果也将包含在返回的行数中.最有可能的是,这是你的问题.
编辑:文档
从MSDN SqlCommand.ExecuteNonQuery:
当插入或更新的表上存在触发器时,返回值包括插入或更新操作影响的行数以及受触发器或触发器影响的行数.