mysqlinputcreate-function

MySQL Create function statement with existing table


I have asked these question before but I think it is better to ask a new question because my old question appears to be slightly different. I didn't mention the existing table and the input there.

I have a table 'item' which contains all the data like prices and inventories from each item. My function should take the input from the actual inventory and item price and convert it into the itemvalue using formula inventory*price. If the itemvalue is negative then the output should be 0, otherwise the positive value should be returned.

CREATE function item_value (inventory int UNSIGNED, price decimal(8,2)) RETURNS DECIMAL(8,2)
BEGIN 
 IF inventory*price < 0 THEN 
  SET itemvalue = 0
 ELSE 
  SET itemvalue = inventory*price
END IF;

The signature of the function:

item_value (inventory int UNSIGNED, price decimal(8,2))

Table item:

item


Solution

  • It appears to me, that your function isn't working, since you do not return anything. Am I right? You should add a return statement...

    CREATE FUNCTION item_value (inventory INT UNSIGNED, price DECIMAL(8,2)) RETURNS DECIMAL(8,2)
    BEGIN 
        DECLARE itemvalue DECIMAL(8,2) DEFAULT 0.0;
    
        IF inventory*price < 0 THEN 
            SET itemvalue = 0
        ELSE 
            SET itemvalue = inventory*price
        END IF;
    
        RETURN (itemvalue);
    END