sqlmysqlcountuser-defined-functions

MySQL User-Defined function Returns wrong result when used with SQL query


I want to find the total account balance for a particular credit card user. Below is the query

CREATE FUNCTION GetAccountBalance(UserID INT) 
RETURNS DECIMAL(10, 2)
BEGIN
    DECLARE totalBalance DECIMAL(10, 2);
    
    SELECT SUM(Balance) INTO totalBalance 
    FROM Accounts 
    WHERE UserID = UserID;
    
    RETURN totalBalance;
END//

But this function returns the total balance of all users and not that particular user. How can I solve this problem? Please help me

Total balance of that particular user


Solution

  • Your parameter name is the same as the field name

    WHERE UserID = UserID;
    

    is always true, so I am guessing this is the reason. Rename your function's parameter and try again.