我正在使用MySQL开发一个ASP.net应用程序,并且有一个与存储过程返回值相关的问题。
这是我的存储过程:
CREATE DEFINER=`pcg`@`%` PROCEDURE `UpdatePreSellerProfile`(
IN UserID INT(11),
IN SellerImageID INT(11),
IN BusinessImageID INT(11),
OUT ProfileUpdated INT(1)
)
BEGIN
SET @Approved = 'APPROVED';
UPDATE user SET
SELLER_IMAGE_ID = COALESCE((SELECT IMAGE_ID FROM image_url WHERE IMAGE_USER_ID = UserID AND IMAGE_ID=SellerImageID),SELLER_IMAGE_ID),
SELLER_BUSINESS_LOGO_ID = COALESCE((SELECT IMAGE_ID FROM image_url WHERE IMAGE_USER_ID = UserID AND IMAGE_ID=BusinessImageID),SELLER_BUSINESS_LOGO_ID)
WHERE (USER_LOGIN_ID = UserID AND USER_PROFILE_STATUS = @Approved);
SET ProfileUpdated = ROW_COUNT();
END当我使用下面的MySQL脚本测试这段代码时,当没有更新时,我总是得到0 (@ProfileUpdated)。
call UpdatePreSellerProfile(@UserID, @SellerImageID, @BusinessImageID ,@ProfileUpdated);但是当我在我的C#代码中检查它时,它总是显示1 (ProfileUpdated)。
if (oMySQLConnecion.State == System.Data.ConnectionState.Open)
{
MySqlCommand oCommand = new MySqlCommand("UpdatePreSellerProfile", oMySQLConnecion);
oCommand.CommandType = System.Data.CommandType.StoredProcedure;
MySqlParameter sqlProfileUpdated = new MySqlParameter("@ProfileUpdated", MySqlDbType.VarString);
sqlProfileUpdated.Direction = System.Data.ParameterDirection.Output;
oCommand.Parameters.Add(sqlProfileUpdated);
oCommand.Parameters.AddWithValue("@UserID", UserID);
oCommand.Parameters.AddWithValue("@SellerImageID", oSeller.SellerImageID);
oCommand.Parameters.AddWithValue("@BusinessImageID", oSeller.BusinessLogoID);
oCommand.ExecuteNonQuery();
Int16 ProfileUpdated = Convert.ToInt16(oCommand.Parameters["@ProfileUpdated"].Value);
if (ProfileUpdated > 0) // <<-- Should be greater only if it is updated is sucessfull
{
oDBStatus.Type = DBOperation.SUCCESS;
oDBStatus.Message.Add(DBMessageType.SUCCESSFULLY_DATA_UPDATED);
}
else
{
oDBStatus.Type = DBOperation.ERROR;
oDBStatus.Message.Add(DBMessageType.ERROR_NO_RECORDS_UPDATED);
}
oMySQLConnecion.Close();
}为什么MySQL脚本与C#代码之间存在差异?
发布于 2020-01-12 22:00:47
除非您设置了UseAffectedRows连接字符串选项,否则默认为false。This means
如果为
false(默认值),则连接报告将找到行,而不是已更改(受影响)的行。设置为true将仅报告UPDATE或INSERT … ON DUPLICATE KEY UPDATE语句实际更改的行数。
此外,还可以从documentation of the ROW_COUNT function
对于UPDATE语句,
-rows值缺省情况下是实际更改的行数。如果在连接到mysqld ed时将
CLIENT_FOUND_ROWS标志指定为mysql_real_connect()。注意:这与UseAffectedRows相同,affected rows值是“找到”的行数;也就是说,与WHERE子句匹配。
因此,存储过程中的UPDATE user语句将返回查询找到的行数,而不是实际更新的行数。
要解决此问题,请执行以下任一操作:
UseAffectedRows=true;;这可能会导致更改其他UPDATE查询。WHERE子句添加更多条件,例如WHERE ... AND SELLER_IMAGE_ID != SellerImageID AND SELLER_BUSINESS_LOGO_ID != BusinessImageID,以确保只有在确实需要更改行时才能找到并更新该行。https://stackoverflow.com/questions/59701480
复制相似问题